Why AJAX call to Servlet (async) is executed multiple times? - java

I'm doing a simple login application with servlets and AJAX. I'm curious why the AJAX call is fired multiple times when I specified async as true. When async is specified as false, the call is made just one time.
Sample:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form id="flogin" class="panel">
<section class="panel-head">
</section>
<section class="panel-body">
<input type="text" id="txt-username" class="textbox" placeholder="Usuario o email"/>
<input type="password" id="txt-password" class="textbox" placeholder="ContraseƱa"/>
<section class="form-action-group">
<button type="submit" id="btn-login" class="btn btn-primary">Ingresar</button>
</section>
</section>
</form>
<script src="assets/js/login.js"></script>
</body>
</html>
JavaScript source:
document.addEventListener("DOMContentLoaded", init, false);
function init() {
var form = document.querySelector("#flogin");
form.addEventListener("submit", handleLogin, true);
function handleLogin(e) {
e.preventDefault();
var txtUsername = document.querySelector("#txt-username");
var txtPassword = document.querySelector("#txt-password");
var userdata = '{"username":'+txtUsername.value+',"password":'+txtPassword.value+'}';
loginByAjax(userdata);
resetForm(form);
}
function loginByAjax(data) {
var message;
var request = new XMLHttpRequest();
request.open("POST", "LoginController", false);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if(request.readyState != 4 || request.status != 200) {
message = request.responseText;
} else {
message = request.responseText;
}
console.log(message);
};
request.send("userdata="+data);
}
}
And the servlet:
package com.company.controllers;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Logger;
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 com.company.utils.JsonUtils;
#WebServlet(asyncSupported=true, urlPatterns={"/LoginController"})
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger("LoginLogger");
public LoginController() {
super();
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
String strJson = request.getParameter("userdata");
Map<String, Object> userData = JsonUtils.getMapFrom(strJson);
String username = (String) userData.get("username");
String password = (String) userData.get("password");
if(username.equals("Duke") && password.equals("Duke777")) {
writer.print("Usuario correctamente identificado");
} else {
writer.print("Usuario o contraseƱa incorrectas");
}
writer.flush();
writer.close();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
processRequest(request, response);
} catch(ServletException | IOException e) {
logger.warning(e.getLocalizedMessage());
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch(ServletException | IOException e) {
logger.warning(e.getLocalizedMessage());
}
}
}
Async AJAX call image: http://i.imgur.com/SbxUBsz.png
Can someone explain to me why this happens?

The true is the servlet is not called multiple times, what happen is when you make an async call the onreadystatechange will be called several times during the ajax request phase, since the connection is stablished until the connection is closed, there are 4 steps in the ajax call and each of them call the onreadystatechange you can know the step with the request.readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
You're logging the message in each of these steps you could log at the message at the end of the ajax call in this way.
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {//if finish the ajax call and the status is ok
message = request.responseText;
console.log(message);
};
console.message('Checking the progress of the ajax call: ' + request.readyState);
}
Your could check more information in the MDN XMLHttpRequest

Related

FilterChain#doFilter does not redirect to desired page

I have implemented a simple web app with user authentication, and tried to add a filter to redirect to the login page, when the user is not logged in. The filter does the redirection properly, when it is supposed to, but it keeps redirecting to the login page when a user is logged in too.
Is there any specific method to be called, in case there is no need for redirection (besides filterChain#doFilter), or is there another mistake in my code?
Here are the classes and pages:
login page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login page</title>
</head>
<body>
<form method= "post" action="login" name="Login Form" id="login-form">
<h2>login</h2>
<label for="username">username</label><input name="username" type="text" id="username" />
<br>
<label for="password">password</label><input name="password" type="password" id="password" />
<br>
<input type="submit" value="login" id="submitButton" />
</form>
</body>
</html>
login handler:
package control;
import model.User;
import repository.DAOFactory;
import repository.UserDAO;
import util.PasswordHasher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
#WebServlet(name = "loginHandler", urlPatterns = {"/login"})
public class loginHandler extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
UserDAO dao = DAOFactory.getInstance().getUserDAO();
String username = request.getParameter("username");
try {
if(dao.validateUserLogin(username,request.getParameter("password"))>0) {
HttpSession session = request.getSession();
session.setAttribute("username",username);
session.setMaxInactiveInterval(30*60);
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(30*60);
response.addCookie(cookie);
User user = dao.getUserByUsername(username);
user.setLastHashedSessionID(PasswordHasher.hashPassword(session.getId(),user.getSalt()));
dao.updateUser(user);
response.sendRedirect("page.html");
}
else
request.getRequestDispatcher("error.html").forward(request,response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
authentication filter:
package control;
import model.User;
import repository.DAOFactory;
import repository.UserDAO;
import util.PasswordHasher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#WebFilter(urlPatterns = {"/page.html"})
public class authenticationFilter implements Filter{
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if(request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
System.out.print("Checking username in session...");
if(session.getAttribute("username") == null) {
System.out.println("FAILED!");
System.out.println("Redirect needed, no username in session!");
req.getRequestDispatcher("login.html").forward(request, response);
return;
}
System.out.println("OK");
User user;
UserDAO dao = DAOFactory.getInstance().getUserDAO();
String username = ((HttpServletRequest) request).getSession().getAttribute("username").toString();
user = dao.getUserByUsername(username);
System.out.print("Checking session ID...");
if(!user.getLastHashedSessionID().equals(PasswordHasher.hashPassword(session.getId(),user.getSalt()))) {
System.out.println("FAILED!");
session.invalidate();
req.getRequestDispatcher("login.html").forward(request,response);
System.out.println("Redirect needed, invalid session!");
return;
}
else {
System.out.println("OK");
chain.doFilter(request, response);
}
}
System.out.println("end of doFilter!");
}
#Override
public void destroy() {
}
}

Servlet getServletContext().getRequestDispatcher shows attributes in url line

I have built a small servlet with two jsp files and a controller.
This is the login.jsp :
<body>
<section class="loginform cf">
<form name="login" action="controller/login" method="get" onsubmit="return validateForm()"
accept-charset="utf-8">
<ul>
<li><label for="username">Username</label> <input type="text"
name="username" ></li>
<li><label for="password">Password</label> <input
type="password" name="password" ></li>
<li><input type="submit" value="Login"></li>
</ul>
</form>
<form action="http://localhost:8080/ToDoListProj" method="get">
<input title="Register" type="submit" value="Not Yet A Member?" formaction="register.jsp"/>
<br/>
</form>
</section>
</body>
and this is the controller:
package il.ac.hit.controller;
import il.ac.hit.model.HibernateToDoListDAO;
import il.ac.hit.model.Item;
import il.ac.hit.model.ToDoListPlatformException;
import il.ac.hit.model.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import antlr.StringUtils;
/**
* Servlet implementation class ToDoListPlatformContrller
*/
#WebServlet("/controller/*")
public class ToDoListPlatformController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ToDoListPlatformController() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
private boolean isAlphaNumeric(String word)
{
return word.matches("[a-zA-Z0-9]+");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getPathInfo();
System.out.println(path);
RequestDispatcher dispatcher = null;
switch(path)
{
case "/login":
{
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username != null && password != null && isAlphaNumeric(username) && isAlphaNumeric(password))
{
List<User> usersList = il.ac.hit.model.HibernateToDoListDAO.getInstance().getUsersList();
for(User user : usersList)
{
if(user.getName().equals(username) && user.getPassword().equals(password))
{
Cookie cookie = new Cookie("UserId", username);
cookie.setPath("/");
response.addCookie(cookie);
request.getSession().setAttribute("UserID", username);
request.getSession().setAttribute("table", HibernateToDoListDAO.getInstance().getItemsList(username));
dispatcher = getServletContext().getRequestDispatcher("/view.jsp");
break;
}
}
}
else
{
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
} catch (ToDoListPlatformException e) {
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
break;
}
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
}
}
when I enter a username and password on the login jsp page and hit submit, both attributes are being shown in the URL line.
this is what I get:
http://localhost:8080/ToDoListProj/controller/login?username=usernamesample&password=passwordasmple
How can I fix that ?
You should change method="get" to method="post".
GET method adds the data to the URL as in your case. Never use get method when deals with auth. forms.
Use Http POST instead of GET:
In the JSP
<form name="login" action="controller/login" method="post"
and in the controller:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// read login data from request like you do now in doGet...
<form name="login" action="controller/login" method="get" , the form uses get ,so the parameters show up in the url ,use method="post". Now remember after making this doPost() will be called , so ou'll have to either copy your code in to doPost() or call doGet() from doPost()
You have to change get to post method
<form name="login" action="controller/login" method="post" onsubmit="return validateForm()"
In get the request parameters are passed to the server by appending
at the end of the url, whereas in a post request form elements or
parameters are passed as a part of HTTP body and does not append at
the end of URL. So whenever we need to send some sensitive information
to server, a post request is sent.
HttpGet is "OK", if you use https instead of http. Https will encrypt your get parameters (but the whole request url may be saved unencrypted in server logs for example, therefore HttpPost would be the method of choice).
In addition to all the answers saying you should use method=post, you could put the code from doGet in a own function, lets say login, so you can use HttpPost and HttpGet at the same time:
private RequestDispatcher login(HttpServletRequest request, HttpServletResponse response) {
String path = request.getPathInfo();
System.out.println(path);
RequestDispatcher dispatcher = null;
switch(path)
{
case "/login":
{
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username != null && password != null && isAlphaNumeric(username) && isAlphaNumeric(password))
{
List<User> usersList = il.ac.hit.model.HibernateToDoListDAO.getInstance().getUsersList();
for(User user : usersList)
{
if(user.getName().equals(username) && user.getPassword().equals(password))
{
Cookie cookie = new Cookie("UserId", username);
cookie.setPath("/");
response.addCookie(cookie);
request.getSession().setAttribute("UserID", username);
request.getSession().setAttribute("table", HibernateToDoListDAO.getInstance().getItemsList(username));
dispatcher = getServletContext().getRequestDispatcher("/view.jsp");
break;
}
}
}
else
{
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
} catch (ToDoListPlatformException e) {
dispatcher = getServletContext().getRequestDispatcher("/wronglogin.jsp");
}
break;
}
return dispatcher;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response).forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response).forward(request, response);
}

Servlet won't redirect to receipt page

So I am stuck at the point where the user clicks a submit button and the page should go to a receipt page and display there information.
Am I blind or should this work?
All of the other redirects work just fine using the method I am using but for some reason it wont go to the receipt page.
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//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;
import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void makeCustomerReceipt(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/receipt.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if("addCustomer".equals(action)) {
addCustomer(response, request);
}
else if("addPet".equals(action)) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
}
}
}
CustomerManagement.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Customer Management</title>
</head>
<body>
<form action="customerServlet" method="post">
First Name:<br>
<input type="text" name="firstName"/><br>
Last Name:<br>
<input type="text" name="lastName"/><br>
Email:<br>
<input type="text" name="email"/><br>
Phone Number:<br>
<input type="text" name="phone"/><br>
Phone Type:<br>
<select name="thePhones" id="selectPhones">
<option selected value="choose">
Select a Phone
</option>
<c:forEach items="${sessionScope.phones}" var="current" >
<option>${current.getPhoneName()}</option>
</c:forEach>
</select><br>
Street Address:<br>
<input type="text" name="streetAddress"/><br>
Apartment Number:<br>
<input type="text" name="apartmentNumber"/><br>
City:<br>
<input type="text" name="city"/><br>
State:<br>
<select name="states" id="states">
<option selected value="Wisconsin">
Select a State
</option>
<c:forEach items="${sessionScope.states}" var="current" >
<option>${current.getStates()}</option>
</c:forEach>
</select>
<input type="submit" value="submit">
</form>
</body>
</html>
To troubleshoot, add response.getWriter().write("..."); return; to the two possible problem places where you are doing nothing now:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
response.getWriter().write("Error: Customer ID could not be parsed to a number");
return; //to exit the function: we don't want to do anything more if we encounter this error
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
makeCustomerReceipt(request, response);
return; //to exit the function: you should always do this after forward or redirect
}
else
{
response.getWriter().write("Error: customer is null");
return; //to exit the function
}
}
}

How to pass multiple values to servlet using Jquery

I have an Html form from that i need to pass values to servlet using jquery and there it will validates the information and returns the result.But when i try to pass the data using jQuery.
The servlet showing that null value received.
<div class="ulogin">
<h2>Login</h2>
<div id="error"></div>
<form action="Login" method="post" id="spsignin">
<input type="text" name="uname" class="text validate[required]" id="name" placeholder="Username"/>
<input type="password" name="pass" class="text validate[required]" id="password" placeholder="Password"/>
<input type="submit" value="" id="memberlogin"/>
</form>
</div>
My javascript file is
$(document).ready(function() {
//Stops the submit request
$("#spsignin").submit(function(e){
e.preventDefault();
});
//checks for the button click event
$("#memberlogin").click(function(e){
//get the form data and then serialize that
dataString = $("#spsignin").serialize();
dataString1 = $("#spsignin").serialize();
var uname = $("input#name").val();
var pass = $("input#password").val();
$.ajax({
type: "POST",
url: "Login",
data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
dataType: "json",
//if received a response from the server
success: function( data, textStatus, jqXHR) {
if(data.success)
{
$("#error").html("<div><b>success!</b></div>"+data);
}
//display error message
else {
$("#error").html("<div><b>Information is Invalid!</b></div>"+data);
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#error").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//disable the button until we get the response
$('#memberlogin').attr("disabled", true);
},
complete: function(jqXHR, textStatus){
//enable the button
$('#memberlogin').attr("disabled", false);
}
});
});
});
And the servlet is
package skypark;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
Boolean success=true;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
String dcn="oracle.jdbc.OracleDriver";
String url="jdbc:oracle:thin:#//localhost:1521/skypark";
String usname="system";
String pass="tiger";
Class.forName(dcn);
return DriverManager.getConnection(url,usname,pass);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uname,pass;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
uname=request.getParameter("uname");
pass=request.getParameter("pass");
Boolean suc;
try {
suc = check(uname,pass);
out.println(suc);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
public Boolean check(String uname,String pass) throws SQLException, ClassNotFoundException
{
ResultSet rs = null;
int i=0;
Connection con=prepareConnection();
String Query="select uname,email from passmanager where pass=?";
PreparedStatement ps=con.prepareStatement(Query);
try
{
ps.setString(1,pass);
rs=ps.executeQuery();
while(rs.next())
{
if (uname.equalsIgnoreCase(rs.getString("uname")) || uname.equalsIgnoreCase(rs.getString("email")))
{
rs.close();
ps.close();
ps = null; con.close();
con = null;
success=true;
i=1;
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
if(i==0)
{
success=false;
}
return success;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
I think error is with jquery. please any one help me to overcome from this...
The problem is with this line:
data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass)
which should be
data: 'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass)
note the missing + after encodeURIComponent(uname)
I spot one little error on your Ajax script, your ampersand sign is not part of the string:
data:'uname=' + encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
should be
data:'uname=' + encodeURIComponent(uname) + '&pass=' + encodeURIComponent(pass),
If that doesn't fix it then here's few more things you can check:
Check you only have one input element with id 'name' on your html
Check your request went to right servlet on your servlet mapping
Check you don't have any filters that intercepts and modify / redirect requests
Other than that your code seem fine
well the issue has been cleared already but other than passing the values one by one you can submit the whole form at once ,have a look at this .
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and you form would be like this
<form id="tempForm" enctype="multipart/form-data">
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="file" name="" id="" />
</form>
and you can find the plug in enter link description here

uploading file using ajax and servlet

i'm getting message "File not found". please help me.
here id my code
index.jsp
<html>
<head>
<title>Ajax File Upload</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_frm").submit(function(){
//remove previous class and add new "myinfo" class
$("#msgbox").removeClass().addClass('myinfo').text('Validating Your Form ').fadeIn(1000);
this.timer = setTimeout(function () {
$.ajax({
url: 'uploads',
enctype: 'multipart/form-data',
data: 'filename='+ $('#file').val(),
type: 'post',
success: function(msg){
$("#msgbox").removeClass().addClass('myinfo').text(msg).fadeIn(1000);
}
});
}, 200);
return false;
});
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="login_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form name="login_frm" enctype="multipart/form-data" id="login_frm" action="" method="post">
<div id="login_box">
<div id="login_header"> Citizen Login </div>
<div id="form_val" style="background-color:black; height:80px;">
<div class="label">Upload Pic :</div>
<div class="control"><input type="file" name="file" id="file"/></div>
<div id="msgbox"></div>
</div>
<div id="login_footer">
<label>
<input type="submit" name="upload" id="upload" value="Upload" class="send_button" />
</label>
</div>
</div>
</form>
</body>
</html>
now, this is my servlet
uploads.java
package fileupload;
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.util.List;
import java.util.Iterator;
import java.io.File;
import java.util.Random;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import java.util.regex.*;
public class uploads extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
//out.println("items: "+items);
} catch (FileUploadException e) {
e.printStackTrace();
}
FileItem file = (FileItem)items.get(0);
//out.print(file);
Iterator itr = items.iterator();
int noFile=0;
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()){
String name = item.getFieldName();
String value = item.getString();
} else {
try {
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
String finalimage = buffer.toString()+"_"+r+domainName;
File savedFile = new File("C:/tmp/"+"images\\"+finalimage);
item.write(savedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
out.print(noFile+" File(s) Uploaded !!");
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#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>
}
same code is running perfectly without ajax.
use ajaxfileupload library to upload file using ajax.
below link may help you to upload file using ajax.
http://www.phpletter.com/Our-Projects/AjaxFileUpload/
You can have a look for this ;)
Ajax File Upload to Java Servlet

Categories

Resources