Ajax Login Validation for JSP

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");
%>

Demo Of the projectis here

Download source files for project here

About these ads

24 Responses to Ajax Login Validation for JSP

  1. Amit says:

    superb login page!!!!!

  2. Ning says:

    hi. why when I connect to the database it does not run properly. Although it always login the return value is ERROR?

  3. m says:

    im getting error… pl help me

  4. karthik says:

    if we enter wromg password and username …it will validate and got success page……!

  5. naveen says:

    if i enter wrong password also it is validate and got success page

    help me i am new to ajax

    thanks in advance

  6. 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/

    • Prashant says:

      please refresh the page after you click back.. actually after you back, it is loading the page from temporary.

  7. Karl says:

    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”;
    }
    }
    }

    ************************************************************************

  8. Green says:

    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 .

  9. Gunel says:

    Hi prashant. It is intersting for me that, why you kill the seesion in logout.jsp?

  10. Arif says:

    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.

  11. pharock0345 says:

    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…

  12. Pingback: Ajax form submission with jquery.validate.js and jquery.form.js? | BlogoSfera

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 182 other followers

%d bloggers like this: