uploading file using ajax and servlet - java

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

Related

not able to upload file into server using jsp

I'm trying to develop a Java web application wherein I need to upload files into the server. I am using Xampp tomcat server which is integrated into eclipse application. Upon selecting the file to upload, I'm getting File Upload failed status message in the next page. This is my code
fileUpload.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>FileUpload</title>
</head>
<body>
<form action="MsgProcessorServlet" method="post" enctype="multipart/form-data" id="uploadForm">
<input type="file" name="file"/>
<input type="hidden" name="formType" value="uploadXML"/>
</form>
<p>
<button type="submit" form="uploadForm" id="Upload">Upload</button>
</p>
</body>
</html>
MsgProcessorServlet.java
package com.servlet;
import java.io.IOException;
import java.util.List;
import java.io.File;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class MsgProcessorServlet
*/
#WebServlet("/MsgProcessorServlet")
#MultipartConfig
public class MsgProcessorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MsgProcessorServlet() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(request.getParameter("formType"));
if(request.getParameter("formType").equals("buildNew")) {
request.setAttribute("message", "Files generated successfully");
RequestDispatcher req = request.getRequestDispatcher("buildNewResult.jsp");
req.forward(request, response);
}
else if(request.getParameter("formType").equals("uploadXML")) {
request.setAttribute("message", "File Upload failed");
if(ServletFileUpload.isMultipartContent(request)) {
System.out.println("came here1");
List<FileItem> multiparts = null;
try {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(5 * 1024 * 1024);
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(5 * 1024 * 1024);
multiparts = servletFileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("multiParts size: ");
System.out.println(multiparts.size());
for(FileItem item : multiparts) {
System.out.println("came here2");
if(!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println(fileName);
try {
request.setAttribute("message", "File Uploaded successfully");
item.write(new File("./" + fileName));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
RequestDispatcher req = request.getRequestDispatcher("fileUploadResult.jsp");
req.forward(request, response);
}
}
}
The multipleParts list of type FileItem is not getting populated upon calling parseRequest method of ServletFileUpload.
Try this. Working code.
Fileupload.java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet to handle File upload request from Client
* #author Javin Paul
*/
public class Fileupload extends HttpServlet {
private final String UPLOAD_DIRECTORY = "C:/uploads";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher(/* redirect according to your need. */).forward(request, response);
}
}
Index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="Fileupload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>

Send ajax post request to servlet

I can not send a simple request to the servlet to jQuery tools. But at the same time if I go through the form, then everything works on hurray. Here is the index.html from which I want to send the user's login. Login.js, in which I form the request itself, SerletStore.java itself servlet. And the structure of the whole project.
login.js
$(document).ready( function(){
$("#login-submit").click(function(){
var data = {
username: $("#user").prop("value")
}
$.ajax({
method: "POST",
url: "http://localhost:8080/ChallengeClient/store",
data: {
username: $("#user").prop("value")
},
success: function(data) {
alert('Success');
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
}).done(function() {
alert('Success');
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/login.js"></script>
</head>
<body>
<div id="login">
<form name="form-login">
<span class="fontawesome-user"></span>
<input type="text" id="user" name="username" placeholder="Имя пользователя">
<span class="fontawesome-lock"></span>
<input type="password" id="pass" placeholder="Пароль">
<input type="submit" id="login-submit" value="Вход">
</form>
</div>
</body>
</html>
ServletStore.java
package servlet;
import server.service.HelloWebService;
import server.service.HelloWebServiceImplService;
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 java.io.IOException;
#WebServlet(name="store", urlPatterns = "/store")
public class ServletStore extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// подключаемся к тегу service в wsdl описании
HelloWebServiceImplService helloService = new HelloWebServiceImplService();
// получив информацию из тега service подключаемся к самому веб-сервису
HelloWebService hello = helloService.getHelloWebServiceImplPort();
// обращаемся к веб-сервису и выводим результат в консоль
/*String error = hello.getHelloString("!! Challenge !!");*/
String error = "";
String username = (String) req.getParameter("username");
if (username.equals("")) {
error = "Не было введено имя пользователя";
}
req.setAttribute("error", "Не было введено имя пользователя");
req.getRequestDispatcher("jsp/loginError.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

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

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

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

Categories

Resources