Please check the below code
JSP
<%--
Document : index
Created on : Sep 8, 2015, 10:13:49 AM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page contentType="text/html" import="java.util.Date" %>
<%#page contentType="text/html" import="java.sql.Timestamp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function time()
{
var elem = document.getElementById("hiddenTxt");
elem.value = "<%= new Date().getTime()%>";
}
</script>
<script type="text/javascript">
function time2()
{
var elem = document.getElementById("hiddenTxt");
elem.value = Date.now();
}
</script>
<script type="text/javascript">
function time3()
{
alert(<%= new Date().getTime()%>);
}
</script>
</head>
<body>
<button onclick="time3()" value="click" >Click</button>
<form action="TimestampClass" method="post" onsubmit="time2()">
Name: <input type="text" name="nameTxt">
<input type="hidden" name="hiddenTxt" id="hiddenTxt" >
<input type="submit" value="Submit">
</form>
</body>
</html>
Servlet
package test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
/**
*
* #author Yohan
*/
public class TimestampClass extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// long currentTimeMillis = System.currentTimeMillis();
// Timestamp timestamp = new Timestamp(currentTimeMillis);
// System.out.println(currentTimeMillis);
// System.out.println(timestamp);
String name = request.getParameter("nameTxt");
long timeStampLong = Long.parseLong(request.getParameter("hiddenTxt"));
PrintWriter out = response.getWriter();
out.println(name);
out.println("<br>");
out.println("Script Time: "+getSQLCurrentTimeStamp( timeStampLong));
out.println("<br>");
out.println("Normal Time: "+getSQLCurrentTimeStamp());
}
public static java.sql.Timestamp getSQLCurrentTimeStamp(long timeStampLong)
{
Timestamp t2= new Timestamp(timeStampLong);
return t2;
}
public static java.sql.Timestamp getSQLCurrentTimeStamp()
{
java.util.Date date= new java.util.Date();
Timestamp t= new Timestamp(date.getTime());
System.out.println(t);
return t;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
All I want is to send the current time of the client PC to the server. I have tried both Javascript and Java inside JSP.
But there is an issue with the Javascript. I have my server in amazon EC2 US-West and I am in Sri Lanka. The time difference is +5.30GMT
When I deploy the code, the javascript simply gets the time of the server, not the time in my computer.
I tried using Java inside JSP and it is having another issue. That is, no matter where I place the new Date.getTime(), it is always getting the time the web page was loaded and it won't change even after minutes.
What am I doing here wrong? All I want is to send the current time of the client to the Server side Servlet.
The snippet:
<%= new Date().getTime()%>
will always get the server time, so forget about using that.
To get the client timestamp you need to use JavaScript. In your HEAD section add this (within script tags of course):
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
This sets up the Date.now function in case the client uses Internet Explorer 8, which doesn't know Date.now
I don't know how JavaScript optimizes code. Maybe you could try this to see if it makes a difference if the Date is determined inside a function or not:
<form action="TimestampClass" method="post" onsubmit="document.getElementById('hiddenTxt') = Date.now();">
Name: <input type="text" name="nameTxt">
<input type="hidden" name="hiddenTxt" id="hiddenTxt" >
<input type="submit" value="Submit">
</form>
Try to use JS function to get time
function time3(){
alert(new Date().getTime());
}
Related
I'm new to NetBeans and JSP Servlet and I'm trying to create a Web Application using JSP Servlet in Apache NetBeans 11.1 and I keep getting this error:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Error instantiating servlet class [controller.NewServlet]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Error instantiating servlet class [controller.NewServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
I tried uninstalling Netbeans and Tomcat server and reinstall them but still, got the same error.
This is what my Web.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>controller.NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
My servlet
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author sagarluitel
*/
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try ( PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Sign up here</h1>
<form action="NewServlet" method="post" onsubmit="return validateForm();">
<input type="hidden" name="action" value="signup">
<label>First Name</label>
<input type="text" id="firstName" name="firstName" placeholder="First Name" required><br>
<label>Last Name</label>
<input type="text" id="lastName" name="lastName" placeholder="Last Name" required><br>
<label>Email</label>
<input type="email" id="email" name="email" placeholder="Email" required><br>
<label>Password</label>
<input type="password" id="password" name="password" placeholder="Password" required><br>
<i>Use 8 or more characters with a mix of letters, numbers & symbols</i><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>
File path:
WebApplication
Web Pages
META-INF
WEB-INF
web.xml
index.jsp
Source Packages
controller
NewServlet.java
My problem is not same as this (HTTP Status 500 - Error instantiating servlet class pkg.coreServlet) because My src folder is not in the WEB-INF directory.
Can someone please help me with this, I don't know what am I missing or doing wrong. I'm using macOS Catalina, got the same error while using the previous version of Mac as well.
the problem to when I fill in the form it calls a servlet, which displays the correct information, when the user clicks the back button it seems to call the servlet on that page with the value null. How do i make it so it reloads the page so the user can refill in the form.
SetTimeZone.xhtml
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SetTimeZone</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div>
<form name ="SetTimeZone" method="post" action="SetTimeZoneServlet">
Set Time Zone: <input type="text" name="timeZone"/><br></br><br></br>
<input type ="submit" value="Submit" name="submit"/>
</form>
</div>
</body>
public class SetTimeZoneServlet extends HttpServlet {
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
TimeZoneBean bean = new TimeZoneBean();
String city = request.getParameter("timeZone");
bean.setCity(city);
String temp = bean.checkCity();
String value = "";
if ("error".equals(temp)) {
value = "Sorry no information is availible for " + city;
} else {
value = "The current time in " + city + " is " + bean.getTime();
}
try (PrintWriter out = response.getWriter()) {
response.setContentType("text/html;charset=UTF-8");
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet OrderFormServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>" + value + "</p>");
out.println("<form name=\"SetTimeZone.xhtml\" method=\"post\" name=\""
+ "SetTimeZoneRedirectServlet\"> ");
out.println("<input type =\"submit\" value=\"Back\"/ name=\"back\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
public class SetTimeZoneRedirectServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("SetTimeZone.xhtml");
}
}
The output i get after the redirect back to the page is;
Sorry no information is available for null.
Try Using the GET Instead of POST
This may solve your problem
By using the POST method for your form you may encounter this problem. As #visray suggested, you need to override the doGet() Servlet method for the GET method to work correctly.
POST method should be used when dealing with database changes, so in your case GET is appropriate.
I am developing a small sql servlet application that takes in a SQL command from a text area in an html page, sends the command to a servlet that makes an sql connection and puts in the resultset into an arraylist. I have all of that down, and i can print column names to the browser in the java servlet class. One thing i need to do is print the results into a table using a JSP page. The JSP page will look just like the html page we first used. I can not figure out how i am going to get the arraylist from the servlet to the JSP page to be displayed to the user.
Here is the HTML page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
</font>
</body>
</html>
and here is the servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
/**
*
* #author KJ4CC
*/
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
Connection connection;
Vector<String> columnNames = new Vector<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String command = request.getParameter("command");
out.println("<!DOCTYPE html>");
out.println("<html>");
sqlConnection(command);
//prints out column names into the browser.
out.println(columnNames);
}
}
public void sqlConnection(String command){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/project3";
String user = "root";
String pass = "Brandy?1994";
ResultSet rs;
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(url,user,pass);
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stmt;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery(command);
int colNum = rs.getMetaData().getColumnCount();
for (int i = 0; i < colNum; i++) {
columnNames.add(rs.getMetaData().getColumnLabel(i+1));
}
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Here is the start of the JSP page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
<%
DO TABLE STUFF HERE TO OUTPUT SQL RESULTS
%>
</font>
</body>
</html>
I think i will create a javaBean to store the arrays so that the JSP page can access the column arraylist. Then use a for loop to iterate through the array list so that i can create the table columns. how could i link the JSP page to the servlet so that if can get the information needed?
I have to do the sql connection in the servlet and cannnot make the connection in the JSP page.
In your servlet method, set attribute in page context as below
HttpServletRequest req = (HttpServletRequest)request;
.... // find out what to put
req.getPageContext.setAttribute('some', objectYouFound);
In your jsp, use el to access the variable:
${some}
In the servlet, store the data in a request attribute:
request.setAttribute("rows", rows);
In the JSP, use the JSTL to loop over the rows:
<c:forEach var="row" value="${rows}">
...
</c:forEach>
Do NOT use Java scriptlets in your JSP.
You have few issues with your current code:
(1) A single servlet instance will be shared across all request threads, so you should NOT create the instance variables for a servlet class i.e.,
Connection connection;
Vector<String> columnNames = new Vector<String>();
These two variables should be created inside your processRequest() method so that they will be local to each request thread.
(2) You are ONLY querying the META DATA of the table, so you can display only column names, but if you wanted to fetch the data as well, you need to use resultSetObj.hasNext() and then use next() method like below:
while (rs.hasNext())
{
String X = rs.getString("empno");
//Retrieve all data
//add to a bean object
//add to list
}
//Now return the list which contains the data
You can look at here for a good example.
(3) Use the request.setAttribute to set the results to the request object and then you can retrieve to the next JSP (results) page.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I've got a page here. When I click the submit button, I get the 404 page saying:
HTTP Status 404 - /Email/EmailGet
type Status report
message /Email/EmailGet
description The requested resource is not available.
Apache Tomcat/7.0.47
Code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="EmailGet" method="GET">
Email: <input type="text" name="email"> <br> Password: <input
type="password" name="password"> <br> <input
type="submit" value="Submit">
</form>
</body>
</html>
Here's the EmailGet code:
package email;
import java.io.IOException;
import javax.mail.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Controller
*/
#WebServlet("/EmailGet")
public class EmailGet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public EmailGet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets the entered email and password
String username = request.getParameter("email");
String password = request.getParameter("password");
//Creates the session and sets the session attributes
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
RequestDispatcher dispatcher;
//Calls the setCredentials method to check if entered credentials are valid
boolean result = SendSMTPMail.setCredentials(username, password);
//if valid, forwards to send page
if (result == true) {
dispatcher = request.getRequestDispatcher("send.jsp");
dispatcher.forward(request, response);
}
//if not valid, forwards to index page with error message displayed
else {
dispatcher = request.getRequestDispatcher("indexerror.jsp");
dispatcher.forward(request, response);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Any ideas? It used to forward the page fine, but seems not to be working now.
Each jsp page runs fine individually, it's just the forwarding that isn't working.
It seems. . . that the requested page does not exist. I don't know the names of you files, so i can only guess that you have a typo somewhere, try to check your url bar and check if this is really the url you wanted.
I am trying to pass basic values such as id from jsp to the servlet through ajax. I tried everything but only null is being passed. Even console.log(val) does not print anything to browser console.
My understanding is: Web page has form values which onsubmit calls js file. js has ajax which calls the servlet and passes the data of the form. The servlet grabs data from ajax by request.getParameter(val)
Here is my code:
Main.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>
<form method="post" action="Main" id="firstform">
<h1>Enter name:</h1>
<input type="text" name="id" id="id" />
<input type="submit" name="submit"/>
</form>
</body>
</html>
main.js
var form = $('#firstform');
console.log("gi");
form.submit(function()
{
$.ajax({
url: 'Main',
data: form.serialize(),
type: 'post',
success: function(data){
console.log(data);
}
});
//return false;
});
Main.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Main
*/
#WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Main() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int ids;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String val = request.getParameter("id");
System.out.print(val);
if(val != null){
ids = Integer.parseInt(val);
out.print(ids); //
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
**Problems:
1)values passed from jsp to servlet
2)console.log doesnt print anything on browser console
1) works but 2) still doesnt.**
in main.js type is type: 'post' and you have written code in get method
do type:'get'
there is no name attribute in your input field. when you are doing
String val = request.getParameter("id");
then in servlet then it will search for the input field having name="id" but in your form there is nothing so it will return null;
give name to the input field like
<input type="text" id="id" name="id"/>
also as sanjay has said your ajax has type post so change it to get as well
Just for the console.log(data) problem, may be $.ajax() function get confused with response type, try this:
Ajax
$.ajax({
url: 'Main',
data: form.serialize(),
type: 'post',
dataType:'text/plain',
success: function(data){
console.log(data);
}
});
Servlet
response.setContentType("text/plain;charset=UTF-8");