Simple login application with j2ee (servlet)

 

Hello friends! Here I will tell how to create a login application in java using a simple Servlet. Generally in a login application we validate a user against the existing user credentials in the database. If the username and password match with any existing records in the database, then user is logged-in the database, else “Username or password mismatch” error is shown to the user.

When we run the “LoginProject” the following things happen.
Steps:
1)When the application is ran in the browser, WebContainer checks the web deployment descriptor (web.xml) and checks for the tag . Then web container picks the jsp file mentioned in the tag and renders it in the web browser. Here in our application we have given “login.jsp” as welcome file. So, when we run the application “login.jsp” file is rendered first.

2)When user gives details (username and password) and clicks on login button the request goes to the WebContainer with the URL (action attribute mentioned in form tag). Web Container checks “web.xml” file for the matching URL. If found it picks the Servlet class name from tag and calls the doGet()/doPost() method of the Servlet class. Here we are making POST request, hence doPost() method is called.

3)In doPost() method after retrieving the username and password, doLogin() method of LoginService class is called.

4)In doLogin() method we get the database connection(here we are using MYSQL database) and querying the database for any matching record having the username and password entered by the user. If any record exists then we send SUCCESS else FALSE to the LoginServlet class.

5)Based upon the response from doLogin() method we redirect to the respective jsp page, i.e. to success.jsp or failure.jsp.

Workflow image
Databse
Create USER table with below sample code and insert one demo record.

CREATE TABLE USER (
     id INT NOT NULL AUTO_INCREMENT,
     USER_NAME VARCHAR2(40) NOT NULL,
     PASSWORD VARCHAR2(40) NOT NULL,
     PRIMARY KEY (id)
);

//Insert Demo data into the User Table
INSERT INTO USER ('id', 'USER_NAME', 'PASSWORD') VALUES (NULL, 'demo', 'demo');

Application Folder Structure
Simple login application with j2ee (servlet)

Below i will described step by step working flow of the application.

login.jsp:
This is the home page of the application. It contains a

tag. We have username, password and a Login button in the form. The action attribute of the
tag contains “login”, so when we click on the login button the form is submitted and request goes to the Servlet that has been configured in “web.xml” file with the url “login”. The method attribute contains ‘post’, hence doPost() method of the servlet will be called.

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>Login application</title>
	</head>
	<body>
		<center>


<form action="login" method="post">
				Username : <input type="text" name="username" /></br>
				Password : <input type="password" name="password" /></br>
				<input type="submit" value="Login" />
			</form>


		</center>
	</body>
</html>

success.jsp
When user successfully logged-in to the application, this jsp is displayed.

<html>
	<body>
		<center>


<h3>You are successfully logged-in</h3>


			<a href="./login.jsp">back</a>
		</center>
	</body>
</html>

failure.jsp
This jsp is displayed when user try to login with wrong username and password.

<html>
	<body>
		<center>


<h3>Username or password is wrong, please try again</h3>


			<a href="./login.jsp">back</a>
		</center>
	</body>
</html>

LoginServlet.java
This is our Servlet. Here we are retrieving the username and password entered by user from HttpServletRequest object. The request parameter name should be same as the input field name given in login.jsp. After getting the username and password we are validating the username or password. If any of those are empty, we are redirecting to failure.jsp page, else we are calling the doLogin() method of LoginServlet class.

package com.loginproject.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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.loginproject.service.LoginService;

public class LoginServlet extends HttpServlet {
	private LoginService service = null;

	public void init(ServletConfig config) throws ServletException {
		System.out.println("initialized");
		service = new LoginService();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		RequestDispatcher rd = null;
		if((username == null || username.isEmpty()) || (password == null || password.isEmpty())){
			rd = request.getRequestDispatcher("failure.jsp");
			rd.forward(request, response);
		}else{
			String message = service.doLogin(username, password);
			if(message.equals("SUCCESS")){
				rd = request.getRequestDispatcher("success.jsp");
				rd.forward(request, response);
			}else if(message.equals("FAILURE")){
				rd = request.getRequestDispatcher("failure.jsp");
				rd.forward(request, response);
			}
		}
	}
}

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 login.jsp page. Here we are using MySQL database. The script to create table and insert one user details are given above.

package com.loginproject.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 {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Login","root","admin");
			PreparedStatement statement = con.prepareStatement("SELECT USER_NAME, PASSWORD FROM USER WHERE USER_NAME = ? AND PASSWORD = ?");
			statement.setString(1, username);
			statement.setString(2, password);
			
			ResultSet rs = statement.executeQuery();
			if(rs.next()){
				message = "SUCCESS";
			}else{
				message = "FAILURE";
			}
		} catch (Exception e) {
			message = "FAILURE";
			e.printStackTrace();
		}
		return message;
	}
}

web.xml
This is called the web deployment descriptor. This is the file where we register Servlet class.When a request comes from browser, Web Container uses this file to indentify which servlet to call .

<?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>LoginProject</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.loginproject.controller.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
</web-app>

COMMENTS ( 25 )

UteKCriton says:

Hi, yes this article is really nice and I have learned lot of things from it
about blogging. thanks.

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