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
Related
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);
}
I'm trying to capture the data I enter from my form. Once I hit the submit button but I'm having difficulties. Below is my simple code. I'm trying to work on a registration page that captures all the info about a person. Some of the data have a drop down menu and radio button. I want to capture and store everything in the database(mysql).
My servlet code:
package com.Registration.Controllers;
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 AddUserSevelet
*/
#WebServlet("/AddUserSevelet")
public class AddUserSevelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddUserSevelet() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter write = response.getWriter();
String username = request.getParameter("uname");
String password = request.getParameter("pass");
String country = request.getParameter("country");
AddUser register =new AddUser();
if (register.adduser(username, password, country)){
write.println("You Have Been Registered Successfully");
} else {
write.print("ERROR WHILE LOADING");
}
}
}
my adduser class
package com.Registration.Controllers;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class AddUser {
public boolean adduser(String userName,String password,String country){
boolean isRegistered = false;
try{
Connection con = DB_Connection.getConnection();
PreparedStatement psmt = con.prepareStatement("insert into user VALUES(default,?,?,?,?)");
psmt.setString(1, userName);
psmt.setString(2, password);
psmt.setString(3, country);
int success = psmt.executeUpdate();
if(success > 0){
isRegistered = true;
}
}
catch(Exception e){
e.printStackTrace();
}
return isRegistered;
}
}
My HTML code:
<body>
<form action="AddUserSevelet" method="post">
UserName: <input type="text" name="uname"/><br/><hr/>
password: <input type="password" name="pass"/><br/><hr/>
Country: <input type="text" name="country"/><br/><hr/>
<input type="radio" name="color" value="red" checked>red
<br>
<input type="radio" name="color" value="blue" checked>blue
<br>
<input type="radio" name="color" value="white">white
<br/><hr/>
<br/><hr/>
<select name ="cars">
<option value="BMW"> BMW 320i</option>
<option value="BENZ"> Compressor</option>
<option value="Toyota"> Allion</option>
<option value="Audi"> A5</option>
<option value="Jeep"> Cheroki</option>
<option value="Volvo"> Volvo g5</option>
</select>
<input type="submit" value="Register"/><br/><hr/>
</body>
My question is how do I capture the data from the drop down menu and the radio button, if I put change my servlet code to:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter write = response.getWriter();
String username = request.getParameter("uname");
String password = request.getParameter("pass");
String country = request.getParameter("country");
String cars = request.getParameter("cars");
String color = request.getParameter("color");
AddUser register =new AddUser();
if (register.adduser(username, password, country, cars , color)){
write.println("You Have Been Registered Successfully");
} else {
write.print("ERROR WHILE LOADING");
}
My class code:
Connection con = DB_Connection.getConnection();
PreparedStatement psmt = con.prepareStatement("insert into 'user'(?,?,?,?,?) VALUES(default,?,?,?,?,?,?)");
psmt.setString(1, userName);
psmt.setString(2, password);
psmt.setString(3, country);
psmt.setString(4, cars);
psmt.setString(5, color);
Im getting the error:
error while loading and in the console its java.sql.SQLEXCEPTION:No VALUE specified for parameter 6
Kindly help me with sugestions or solutions on how I can capture data and insert it or edit it using servlets. I'm a newbie just trying to learn. Thank you!
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
I am attempting to post data to a servlet where it will be inserted in to a mysql database.
Here is the html form:
<form id="commentForm" name="commentForm" action="http://server.co.uk/dbh" method="POST">
<input type="text" name="name" placeholder="Your name" required="required">
<textarea name="comment" placeholder="Enter your comment here" required="required"></textarea>
<input type="hidden" name="postID" id="postID" value="<%= postID %>">
<input type="submit" name="submit" id="commentSubmit" value="submit">
</form>
The Jquery:
$("#commentSubmit").click(function(e){
var postData = $("#commentForm").serializeArray();
var formURL = $("#commentForm").attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#commentFormWrap").html("<p>Success</p>");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#commentFormWrap").html("<p>error: "+errorThrown+"</p>");
}
});
e.preventDefault(); //STOP default action
$("#commentForm").hide();
});
A simplified dbh servlet:
import javax.servlet.annotation.WebServlet;
...
#WebServlet(description = "Handles connection to MySql database", urlPatterns = { "/dbh" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
postArray = request.getParameterValues("postData");
commentName = postArray[0];
comment = postArray[1];
postID = Integer.parseInt(postArray[3]);
try{
submitComment();
}catch(Exception e){
e.printStackTrace();
}
}
public void submitComment() throws Exception{
try{
sql="INSERT INTO crm_comments (comment_name, comment_content, comment_date, post_id) VALUES (?, ?, NOW(), ?)";
prep = conn.prepareStatement(sql);
prep.setString(1, commentName);
prep.setString(2, comment);
prep.setInt(3, postID);
rs = prep.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
}
Currently the ajax call is returning the error block error:. But nothing as the errorThrown variable.
From what I can see the servlet is written correctly. Is there something wrong between the html and the Jquery ajax call, that it isn't posting the data to the servlet?
postArray = request.getParameterValues("postData");
I think you can replace this with actual field names
commentName = request.getParameter("name");
comment = request.getParameter("comment");
this will solve your problem
According to the jQuery documentation, the serializeArray method returns a JavaScript array of objects. This method will generate a JSON object from your form, that will look like: [{"name":"name",value:"<your name input value>"},{"name":"comment",value:"<your comment>"},{"name":"postID",value:"<postID value>"} ...]. Only the content of the postData variable will be sent: you won't have any reference at all to that postData keyword in your Servlet.
So in your Servlet, the request.getParameterValues("postData"); call seems to be invalid. Try this instead:
commentName = request.getParameterValues("name");
comment = request.getParameterValues("comment");
postID = Integer.parseInt(request.getParameterValues("postID"));
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