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.
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
Create USER table with below sample code and insert one demo record.

     PRIMARY KEY (id)

//Insert Demo data into the User Table

Application Folder Structure
Simple login application with j2ee (servlet)

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

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.

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

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


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


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

			<a href="./login.jsp">back</a>

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


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

			<a href="./login.jsp">back</a>
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 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 {
		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);
			String message = service.doLogin(username, password);
				rd = request.getRequestDispatcher("success.jsp");
				rd.forward(request, response);
			}else if(message.equals("FAILURE")){
				rd = request.getRequestDispatcher("failure.jsp");
				rd.forward(request, response);
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 {
			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();
				message = "SUCCESS";
				message = "FAILURE";
		} catch (Exception e) {
			message = "FAILURE";
		return message;

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="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">


UteKCriton says:

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


Leave a comment


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