Login application using JAVA, J2EE(Servlet), AJAX and jQuery

 

Today i am going to tell you how to create a login application using J2EE, AJAX and jQuery. AJAX is generally used in a web application to modify or update or to perform certain task without reloading the web page. jQuery is the JavaScript library which makes it easier for handing various JavaScript functionalities like event handling, AJAX, document traversing etc. Here I am modifying the “LoginProject” application from previous post to have jQuery and AJAX support. So, the application flow remains same here, but instead of reloading the home.jsp we will make AJAX call to validate user against database.

Resources Required:
1) mysql-connector.jar – For establishing connection to the Database from our application.
2) jquery-1.11.3.min.js – For using jQuery in our application.

Database:
Use the following script to create USER table.

CREATE TABLE USER(USER_NAME VARCHAR2(40), PASSWORD VARCHAR2(40));

Use the following script to enter one user into the database.

INSERT INTO USER VALUES(‘user’,’pwd’);

Application Folder Structure:
Login-application-using-JAVA-J2EE(Servlet)-AJAX-and-jQuery

web.xml
This file is known as web deployment descriptor. When the application is deployed WebContainer/ Servlet container reads this file first. Here we have configured “home.jsp” as the welcome file. So when we run the application “home.jsp” is loaded into the browser.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AjaxLoginApp</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.ajaxexample.controller.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/loginRequest</url-pattern>
  </servlet-mapping>
</web-app>

home.jsp
This is the jsp where we have used jQuery to validate the username and password from user and to make AJAX call. Here as we are using AJAX call to perform the login operation we don’t necessarily need a <form> tag. Instead we can send the values as JSON string.

$.ajax({ ……..}); is the jQuery function which is used to make AJAX call. Here “url” acts as the “action” attribute of the <form> tag, i.e. this indicates which servlet should process the request made by AJAX call. “method” indicates which request to make, i.e. GET or POST (GET is default method). “data” specifies the data sent to the server. “success” indicates successful execution of the AJAX call.

<%@ 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>jQuery AJAX example with Java</title>
		<script type="text/javascript" src="./js/jquery-1.11.3.min.js" ></script>
	</head>
	<body>
		<center>
			<div id="divId">
				Username : <input type="text" name="username" id="username"/></br>
				Password : <input type="password" name="password" id="password"/></br>
				<button name="login" id="login">Login</button> 
			</div>
			<div id="messageDiv" style="display:none;"></div>
		</center>
		<script>
			$("#login").on('click', function(){
				var username = $("#username").val();
				var password = $("#password").val();
				if(username == ""){
					$('#messageDiv').css("display","none");
					alert("Username is required");
					return;
				}
				if(password == ""){
					$('#messageDiv').css("display","none");
					alert("Password is required");
					return;
				}
				$.ajax({
					url : "loginRequest",
					method : get,
					data : {
						username : username,
						password : password
					},
					success : function(results){
						if(results != null && results != ""){
							showMessage(results);
							$('#messageDiv').css("display","block");
						}else{
							$('#messageDiv').css("display","none");
							$('#messageDiv').html("");
							alert("Some exception occurred! Please try again.");
						}
					}
				});
			});
			
			//function to display message to the user
			function showMessage(results){
				if(results == 'SUCCESS'){
					$('#messageDiv').html("<font color='green'>You are successfully logged in. </font>")
				}else if(results == 'FAILURE'){
					$('#messageDiv').html("<font color='red'>Username or password incorrect </font>")
				}
			}
		</script>
	</body>
</html>

LoginServlet.java
This is our servlet class which handles the ajax call made from the jsp. Here we are retrieving the username and password from request object and passing them to doLogin() method of service class to perform other tasks.

package com.ajaxexample.controller;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ajaxexample.service.LoginService;

public class LoginServlet extends HttpServlet {
       
    LoginService service = null;
    
    public void init(ServletConfig config)throws ServletException{
    	service = new LoginService();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		String message = service.doLogin(username, password);
		response.getWriter().write(message);
	}
}

LoginService.java
This is the class where we are checking whether any user exists in the Database with the username and password entered by user in “home.jsp” page. Here we are using MySQL database. The script to create table and insert one user details are given above.

package com.ajaxexample.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LoginService {
	public String doLogin(String username, String password){
		Connection con = null;
		String message = null;
		try {
			//loading the driver class
			Class.forName("com.mysql.jdbc.Driver");
			//getting the connection from DriverManager factory Class by passing the connection url and credentials
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Login","root","admin");
			//creating prepared statement for our required query
			PreparedStatement statement = con.prepareStatement("SELECT USER_NAME, PASSWORD FROM USER WHERE USER_NAME = ? AND PASSWORD = ?");
			//setting the parameters
			statement.setString(1, username);
			statement.setString(2, password);
			//executing the prepared statement, which returns a ResultSet
			ResultSet rs = statement.executeQuery();
			if(rs.next()){
				message = "SUCCESS";
			}else{
				message = "FAILURE";
			}
		} catch (Exception e) {
			message = "FAILURE";
			e.printStackTrace();
		}
		return message;
	}
}

COMMENTS ( 10 )

Appreciating the persistence you put into your blog and in depth information you present.
It’s great to come across a blog every once in a while that isn’t the
same unwanted rehashed material. Fantastic read!

I’ve saved your site and I’m including your RSS feeds to my Google account.

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories