Ajax Login Validation for JSP
October 22, 2010 32 Comments
Here i have tried to build a small Ajax validation example, which will check the login validation using Ajax concept of jQuery.
In this example,
login page consist of the User id and password field. On submit, jQuery will send the control to the JSP page(check.jsp) using ajax.
<!--index.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> <!-- ..//JQuery Source\\.. --> <script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script> <!-- ..//JavaScript Code for this page\\.. --> <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 Login ').fadeIn(1000); this.timer = setTimeout(function () { $.ajax({ url: 'check.jsp', data: 'un='+ $('#login_id').val() +'&pw=' + $('#password').val(), type: 'post', success: function(msg){ if(msg != 'ERROR') // Message Sent, check and redirect { // and direct to the success page $("#msgbox").html('Login Verified, Logging in.....').addClass('myinfo').fadeTo(900,1, function() { //redirect to secure page document.location='login.jsp?user='+msg; }); } else { $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox { //add message and change the class of the box and start fading $(this).html('Sorry, Wrong Combination Of Username And Password.').removeClass().addClass('myerror').fadeTo(900,1); }); } } }); }, 200); return false; }); }); </script> <link href="css/style.css" rel="stylesheet" type="text/css" /> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Form</title> </head> <body> <form name="login_frm" id="login_frm" action="" method="post"> <div id="login_box"> <div id="login_header"> Login </div> <div id="form_val"> <div>User Id :</div> <div><input type="text" name="login_id" id="login_id"/><span style="font-size: 10px;">hint : admin</span></div> <div>Password:</div> <div><input type="password" name="password" id="password"/><span style="font-size: 10px;">hint : test</span></div> <div style="clear:both;height:0px;"></div> <div id="msgbox"></div> </div> <div id="login_footer"> <label> <input type="submit" name="login" id="login" value="Login" /> </label> </div> </div> </form> </body> </html>
check.jsp will check the login and return an id if the login is valid or it will send ERROR.
<pre><!--check.jsp--> </pre> <% String user=request.getParameter("un"); String pass=request.getParameter("pw"); int user_id=12; if(user.equalsIgnoreCase("admin") && pass.equals("test") ) { out.print(user_id); } else { out.print("ERROR"); } %>
I am sending ID, because using JavaScript I am redirecting the page to the login page where the session for the login will be created. id will not be visible in the source, so that only valid user can redirected to login.jsp
<!--login.jsp--> <%@page session="true"%> <% String user=request.getParameter("user"); session.setMaxInactiveInterval(24 * 60 * 60); session.setAttribute("user",user); response.sendRedirect("success.jsp"); %>
On success.jsp page one can sign out, where the session will get clear.
<!--success.jsp--> <%@page session="true"%> <% if(session.getAttribute("user")==null) { response.sendRedirect("index.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>Login Success</title> </head> <body> <center> <h1>You are successfully logged in</h1> <h3><a href="logout.jsp">Logout</a></h3> </center> </body> </html>
<!--logout.jsp--> <%@page import = "java.util.Date" session="true"%> <% session.setAttribute("user", null); session.invalidate(); response.sendRedirect("index.jsp"); %>
superb login page!!!!!
hi. why when I connect to the database it does not run properly. Although it always login the return value is ERROR?
hi Ning, did u tried with the downloaded source code?
hi Prashant, i downloaded your source code and run successfully. Thanks for sharing!
i wanna connect db with this soucr code.. help me
can you send me your source project? so that i can go threw it?
im getting sql exception error.. bt u didnt use db it seems
if(msg.match(‘ERROR’))
i too have same problem even after downloading source code …….how to solve this problem plzzz
im getting error… pl help me
if we enter wromg password and username …it will validate and got success page……!
if i enter wrong password also it is validate and got success page
help me i am new to ajax
thanks in advance
have you used then return success?
After logout and clicking on logout button and clicking back button, it come back to page its problem .It is not properly logout.If any solution please mail ,e/
please refresh the page after you click back.. actually after you back, it is loading the page from temporary.
Hi prashant. I really like your ajax validation. Right now, I’m trying to modified your coding. I try to connect with the database. And for database, actually I’m also following your tutorial. But the problem is when I insert null value, it will redirect to success page. Can you check what is wrong with this coding?
*********This is your check.jsp. But with little modification**********
********************************************************************************
*******This is your login_bean.java. But I have change the driver for database connectionr*************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author Prashant
*/
import java.sql.*;
import java.util.*;
@ManagedBean(name=”login_bean”)
@RequestScoped
public class login_bean {
private String username;
private String password;
private String dbusername;
public String getDbpassword() {
return dbpassword;
}
public String getDbusername() {
return dbusername;
}
private String dbpassword;
Connection con;
Statement ps;
ResultSet rs;
String SQL_Str;
//private static String dbURL = “jdbc:derby://localhost:1527/Bookstore;create=true;user=;password=”;
private static String dbURL = “jdbc:derby://localhost:1527/Bookstore;create=true;”; //Check kat database connection, kalau tak sama ubah.
public void dbData(String UName)
{
try
{
//Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Class.forName(“org.apache.derby.jdbc.ClientDriver”).newInstance();
con = DriverManager.getConnection(dbURL);
ps = con.createStatement();
SQL_Str=”Select * from DB_JSF where UNAME like (‘” + UName +”‘)”;
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString(2).toString();
dbpassword=rs.getString(3).toString();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(“Exception Occur :” + ex);
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String checkValidUser()
{
dbData(username);
//int user_id=12;
if(username.equalsIgnoreCase(dbusername))
{
if(password.equals(dbpassword))
return “valid”;
else
{
return “Error”;
}
}
else
{
return “Error”;
}
}
}
************************************************************************
Sorry, this is your check .jsp with little modification
I think this is unsecure. I have found this ID is 12. I found this by fire bug. So now we can login using following url without username and password,
http://prashapplication.appspot.com/ajax_validation/login.jsp?user=12 .
Hi prashant. It is intersting for me that, why you kill the seesion in logout.jsp?
Hello Gunel.. I was just trying to clear the session for while logout.
Hi, I am trying to use your code for login purpose, where ever i am doing even one line modification in check.jsp, its redirect to the success.jsp for both valid and invalid user. Please Help.
Hi Arif, I just checked now.. its working fine for me.
if i enter wrong password also it is validate and got success page
i have just downloaded ur code and run it
please help me…
Pingback: Ajax form submission with jquery.validate.js and jquery.form.js? | BlogoSfera
Hello,
Can I use this method to upload files ?
I mean, when I have in my Form,
can I pass it using ajax : data: ‘file=’+ $(‘#MyFile’).val() ?
Regards,
Ghazi.
Hello,
Can I use this method to upload files ?
I mean, when I have in my Form : input type=”file” id=”MyFile” ,
can I pass it using ajax : data: ‘file=’+ $(‘#MyFile’).val() ?
Regards,
Ghazi.
Hello,
I’am using your code… but when i’am trying to connect to database it’s getting stuck while validating your login… i have done changes in check.jsp by using database connectivity code and here is my check.jsp code…
please help me…..
Thanks in advance
can’t see ur code?
I am also getting same error as u are
Seems like hidden bug ,not properly redirecting
Pingback: how to setup a free minecraft pe server
Pingback: technical dictionary free download