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);
}
Related
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() {
}
}
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 very very new to this. and yeah it's a homework.
I am trying to make an HTML page with a form to send some variables to a servlet and the servlet sends an applete to the same form page. so far i succeeded in sending the applet alone. I tried using jQuery, but i couldn't send the HTML tags. I can only send text.
My code so far:
index.html
<html>
<head>
<title> title </title>
</head>
<body>
<form action = "Servlet">
<input type="text" name="Name" value="" size="5" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
Servlet.java
package ServletPackage;
import java.awt.Font;
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;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
String nm;
nm = request.getParameter ("Name");
PrintWriter mess = response.getWriter();
mess.println("<html>");
mess.println("<head>");
mess.println("</head>");
mess.println("<body>");
mess.println("<b> You've entered Name: </b>" + nm);
mess.println("<p align=center>");
mess.println("<applet code='NameInShape.class' width=200 height=200>");
mess.println("<param name='NAME' value='" + nm + "'>");
mess.println(" </applet>");
mess.println("</p>");
mess.println("</html>");
mess.println("</body>");
mess.close();
}
public static void main( String[] args )
{ }
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
All help appreciated
One way to do it is by using RequestDispatcher to call a .jsp (JavaServer Pages) clone of your index.html with the parameters posted by your form. And don't worry, it's pretty simple to implement. The result will look like the initial page the form still available, but the applet will be called using the specified parameters.
You need to import RequestDispatcher (import javax.servlet.RequestDispatcher;) and then you can do something like this in your doPost method:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("clone.jsp");
rd.forward(request, response);
}
The method rd.forward(request, response); makes the parameters posted to your servlet available on the clone.jsp page, and you can insert them using <%=request.getParameter("ParameterName")%> inside the .jsp page.
For example, after adding the above code in your servlet, you could insert something like this in the clone.jsp page to embed the applet with a parameter received from the index.html form submission:
<applet code=Applet.class width=300 height=300>
<param name=NAME value="<%=request.getParameter("NAME")%>">
</applet>
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