PROGRAMS

How to Develop a Role-based Login Application in Java?

This role-based Java Login example contains JSP, Java servlets, session objects, and MySQL database server. You can go through this link to know how to create a database and tables in MySQL using an open-source software Wamp server. This example is an advanced version of java login page. If you are a beginner and if you are looking for a simple Java login and Registration example you can click on the respective links.

What do you mean by role-based login?

When you want to segregate the access level for each user based on their roles like administrator, teacher, student etc in your application you would want to assign a specific role to each user who is logging in so that it is easier to manage large applications. In this example, you are going to see 3 roles – Admin, Editor, and user.

What is a Session?

HTTP is a stateless protocol which means the connection between the server and the browser is lost once the transaction ends. You cannot really track who made a request and when the request terminated. The session helps us to maintain a state between the client and the server and it can consist of multiple requests and responses between the client and the server. Since HTTP and Web Server both are stateless, you would use some unique information (sessionID) to create a session and this sessionID is passed between server and client in every request and response.

Suggested Read:

Before we begin with actual coding, you may want to take a look at the list of files and JARs used in this example and how they are placed in eclipse IDE (open-source java editor). The numbers in blue color indicate the sequence of execution. Further, you can watch the video for the explanation.

Eclipse directory structure

How to Run this Application?

The following video explains how and where to test this application.

Login.jsp
The JSP contains a simple HTML form to key-in login credentials. In order to login to any application, the user must be registered first. Make use of the registration application to complete the user registration.

<%@ 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</title>
 </head>
 <body>
  <form name="form" action="<%=request.getContextPath()%>/LoginServlet" method="post">

  <table align="center">
  <tr>
  <td>Username</td>
  <td><input type="text" name="username" /></td>
  </tr>
  <tr>
  <td>Password</td>
  <td><input type="text" name="password" /></td>
  </tr>
  <tr>
  <td><span style="color:red"><%=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%></span></td>
  </tr>
  <tr>
  <td></td>
  <td><input type="submit" value="Login"></input><input type="reset" value="Reset"></input></td>
  </tr>
  </table>
  </form>
 </body>
</html>
The Java Login form

LoginServlet.java
The servlet is a controller in the MVC pattern. It acts as a bridge between View and Model i.e. it receives the requests from UI and sends it to model (business logic) and then to the related operation.

package com.login.controller;
import java.io.IOException;

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

import com.login.bean.LoginBean;
import com.login.dao.LoginDao;

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public LoginServlet() {
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
 String userName = request.getParameter("username");
 String password = request.getParameter("password");

 LoginBean loginBean = new LoginBean();

 loginBean.setUserName(userName);
 loginBean.setPassword(password);

 LoginDao loginDao = new LoginDao();

 try
 {
  String userValidate = loginDao.authenticateUser(loginBean);

  if(userValidate.equals("Admin_Role"))
  {
   System.out.println("Admin's Home");

   HttpSession session = request.getSession(); //Creating a session
   session.setAttribute("Admin", userName); //setting session attribute
   request.setAttribute("userName", userName);

   request.getRequestDispatcher("/JSP/Admin.jsp").forward(request, response);
  }
  else if(userValidate.equals("Editor_Role"))
  {
   System.out.println("Editor's Home");

   HttpSession session = request.getSession();
   session.setAttribute("Editor", userName);
   request.setAttribute("userName", userName);

   request.getRequestDispatcher("/JSP/Editor.jsp").forward(request, response);
  }
  else if(userValidate.equals("User_Role"))
  {
   System.out.println("User's Home");

   HttpSession session = request.getSession();
   session.setMaxInactiveInterval(10*60);
   session.setAttribute("User", userName);
   request.setAttribute("userName", userName);

   request.getRequestDispatcher("/JSP/User.jsp").forward(request, response);
  }
  else
  {
   System.out.println("Error message = "+userValidate);
   request.setAttribute("errMessage", userValidate);

   request.getRequestDispatcher("/JSP/Login.jsp").forward(request, response);
  }
 }
 catch (IOException e1)
 {
  e1.printStackTrace();
 }
 catch (Exception e2)
 {
  e2.printStackTrace();
 }
} //End of doPost()
}

LoginBean.java
JavaBeans are classes that encapsulate many objects into a single object. The single object facilitates to access all the members of the bean class.

package com.login.bean;

public class LoginBean {

 private String userName;
 private String password;

 public String getUserName() {
 return userName;
 }
 public void setUserName(String userName) {
 this.userName = userName;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }
}

LoginDao.java
This class is part of the Data Access Object. The Data Access Object (DAO) is used to abstract and encapsulate all access to the data source. The DAO is basically an object or an interface that provides access to an underlying database or any other persistence storage.
In this class, we will validate the username and password entered by the user against the username and password stored in the database during the registration process. Based on the user role, the appropriate role type is assigned.

package com.login.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.login.bean.LoginBean;
import com.login.util.DBConnection;

public class LoginDao {

public String authenticateUser(LoginBean loginBean)
{
 String userName = loginBean.getUserName();
 String password = loginBean.getPassword();

 Connection con = null;
 Statement statement = null;
 ResultSet resultSet = null;

 String userNameDB = "";
 String passwordDB = "";
 String roleDB = "";

 try
 {
  con = DBConnection.createConnection();
  statement = con.createStatement();
  resultSet = statement.executeQuery("select username,password,role from users");

  while(resultSet.next())
  {
   userNameDB = resultSet.getString("username");
   passwordDB = resultSet.getString("password");
   roleDB = resultSet.getString("role");

   if(userName.equals(userNameDB) && password.equals(passwordDB) && roleDB.equals("Admin"))
   return "Admin_Role";
   else if(userName.equals(userNameDB) && password.equals(passwordDB) && roleDB.equals("Editor"))
   return "Editor_Role";
   else if(userName.equals(userNameDB) && password.equals(passwordDB) && roleDB.equals("User"))
   return "User_Role";
  }
 }
 catch(SQLException e)
 {
  e.printStackTrace();
 }
 return "Invalid user credentials";
}
}

Watch a detailed video demonstrating the execution of the code in layman’s terms.

The following image contains the MySQL scripts used for this Role-based java login example.

Make a note of the following:

  • Database Name : customers
  • Table Name : users
MySQL Scripts used in this application

DBConnection.java

We are using the MySQL database in this application. We can use any database server that supports Java. Appropriate driver and connection URLs should be used based on the database you choose.

Note: Don’t forget to add the dependent jar for the database server. In our case it’s mysql-connector-java.jar. The latest MySQL version 8 needs a few tweaks, works perfectly until version 8.

package com.login.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {

 public static Connection createConnection()
 {
 Connection con = null;
 String url = "jdbc:mysql://localhost:3306/customers";
 String username = "root";
 String password = "root123";

 try
 {
  try
  {
   Class.forName("com.mysql.jdbc.Driver");
  }
  catch (ClassNotFoundException e)
  {
   e.printStackTrace();
  }
  con = DriverManager.getConnection(url, username, password);
  System.out.println("Post establishing a DB connection - "+con);
 }
 catch (SQLException e)
        {
        System.out.println("An error occurred. Maybe user/password is invalid");
         e.printStackTrace();
       }
 return con;
 }
}

Admin.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>
<title>Admin Page</title>
</head>
<% //In case, if Admin session is not set, redirect to Login page
if((request.getSession(false).getAttribute("Admin")== null) )
{
%>
<jsp:forward page="/JSP/Login.jsp"></jsp:forward>
<%} %>
<body>
<center><h2>Admin's Home</h2></center>

Welcome <%=request.getAttribute("userName") %>

<div style="text-align: right"><a href="<%=request.getContextPath()%>/LogoutServlet">Logout</a></div>
</body>
</html>

Editor.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>
<title>Editor Page</title>
</head>
<% //In case, if Editor session is not set, redirect to Login page
if((request.getSession(false).getAttribute("Editor")== null) )
{
%>
<jsp:forward page="/JSP/Login.jsp"></jsp:forward>
<%} %>
<body>
<center><h2>Editor's Home</h2></center>

Welcome <%=request.getAttribute("userName") %>

<div style="text-align: right"><a href="<%=request.getContextPath()%>/LogoutServlet">Logout</a></div>

</body>
</html>

User.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>
<title>User Page</title>
</head>
<% //In case, if User session is not set, redirect to Login page.
if((request.getSession(false).getAttribute("User")== null) )
{
%>
<jsp:forward page="/JSP/Login.jsp"></jsp:forward>
<%} %>
<body>
 <center><h2>User's Home</h2></center>
 Welcome <%=request.getAttribute("userName") %>

 <div style="text-align: right"><a href="<%=request.getContextPath()%>/LogoutServlet">Logout</a></div>

</body>
</html>

LogoutServlet.java

We are using the MySQL database in this application. We can use any database server that supports Java. Appropriate driver and connection URLs should be used based on the database you choose.

Note: Don’t forget to add the dependent jar for the database server. In our case it’s mysql-connector-java.jar.

package com.login.controller;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet
{
 private static final long serialVersionUID = 1L;
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  HttpSession session = request.getSession(false); //Fetch session object

  if(session!=null) //If session is not null
  {
   session.invalidate(); //removes all session attributes bound to the session
   request.setAttribute("errMessage", "You have logged out successfully");
   RequestDispatcher requestDispatcher = request.getRequestDispatcher("/JSP/Login.jsp");
   requestDispatcher.forward(request, response);
   System.out.println("Logged out");
  }
 }
}

web.xml

The web.xml is known as a deployment descriptor. It lists all the servlets used in the application. Do remember to give a full class name in the servlet-class.

It features few additional configurations such as a welcome-file name leading to the mentioned file name when this application is loaded.
Also, the session-timeout parameter defines that the session would be active for 10 minutes.

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>JavaLogin</display-name>
 <session-config>
  <session-timeout>10</session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>JSP/Login.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
  <description></description>
  <display-name>LoginServlet</display-name>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>com.login.controller.LoginServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LoginServlet</servlet-name>
  <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>
 <servlet>
  <description></description>
  <display-name>LogoutServlet</display-name>
  <servlet-name>LogoutServlet</servlet-name>
  <servlet-class>com.login.controller.LogoutServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LogoutServlet</servlet-name>
  <url-pattern>/LogoutServlet</url-pattern>
 </servlet-mapping>
</web-app>

The source code can be downloaded from the below link.

Enjoyed the tutorial? Let me know your views. Your comments are always welcome here.

Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. A founder of Krazytech. It's been 10+ years since I am publishing articles and enjoying every bit of it. I want to share the knowledge and build a great community with people like you.

Leave a Comment

View Comments

  • Hi Ravi - I followed your tutorial on youtube "Session and Role based Java Login example". Very helpful and everything is working fine. But for my school exercise I want to change the 3 roles and add 3 additional roles. But as soon as I change e.g. Admin to a different name (in all code and classes) it keeps on saying invalid user. Any tips on how I can change the roles and add additional ones? Thanks in advance!

      • Error message = abhi
        abhi
        Post establishing a DB connection - com.mysql.jdbc.JDBC4Connection@6541f4
        Error - abhi
        Error message = abhi

        this type of error occur everytime....
        help me

        • Your method authenticateUser() is returning the userName instead of Role. Please verify it.

  • I have followed every step of it, but I am getting following error.

    The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

    Path in URL is:http://localhost:8080/Sample/LoginServlet

    Can you tell me what is the problem?

    • Hi Shanmukh,

      Looks like you are maintaining different directory structure. Did you modify the web.xml and action="" attribute in the Login.jsp accordingly?

      Also, look for the welcome-file in the web.xml.

      If you use my code as it is, you should be able to access login form with the URL - http://localhost:8080/LoginRoleSession/

      You can also refer to the video for a clear understanding - https://www.youtube.com/watch?v=swdx5g0X1hk

      Let me know if this does not solve your problem.

          • Yes. It is not able to locate your servlet. In the action just specify LoginServlet as shown in the link http://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern

            1.Hope you are using doPost method and your code look like following
            public class LoginServlet extends HttpServlet {

            public LoginServlet() {
            }

            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            2. Also, try loading servlet-api.jar in the execution path.

            3.you can simply start with a new project by copying code for login and servlet only two files.

        • I want to know if your LoginServlet is being called or is it failing while routing requests to LoginServlet.

          Please add sysout statements in LoginServlet. You can try displaying username input in the beginning of the servlet.

          Have you kept web.xml under WEB-INF folder?
          Are you using request.getContextPath()? Try removing it.

          What tomcat version are you using?

Share
Published by
Ravi Bandakkanavar

Recent Posts

What is Home Automation and How Does It Work?

Who doesn’t want a personal assistant? Someone who can take care of all your home-related…

1 hour ago

Importance of Tracking Customers for Ecommerce Business

Any successful ecommerce business should prioritize customer research. You may improve customer engagement and move…

1 hour ago

5G: Application of Future Information Era

The full name of 5G is the fifth-generation mobile communication technology, which means that mobile…

4 weeks ago

What is a People Search Engine? Benefits and Fun Facts

Have you ever wished to find someone's contact information without asking them directly? Or you've…

1 month ago

5G Wireless Technology

5G simply refers to the next and newest mobile wireless standard based on the IEEE…

2 months ago

The Future of Web Design with Artificial Intelligence

In this article, we look at how Artificial Intelligence is changing the way businesses approach…

2 months ago