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 the java login page. If you are a beginner and looking for a simple Java login and Registration example follow 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 was 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.
Other Java Applications:
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.
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>

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

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 your chosen database.
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 and 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.
Have you enjoyed the tutorial? Let me know your views. Your comments are always welcome here.
I am getting an error:
SEVERE: Allocate exception for servlet [LoginServlet]
java.lang.ClassCastException: class com.login.controller.LoginServlet cannot be cast to class jakarta.servlet.Servlet (com.login.controller.LoginServlet is in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @63787180; jakarta.servlet.Servlet is in unnamed module of loader java.net.URLClassLoader @70177ecd)
As soon as I enter login credentials, I get the above error that LoginServlet is not a servlet, even though I have extended LoginServlet with HttpServlet.
Please suggest a solution.
Hi Ayush,
Please check on 2 things.
1. Whether you have uploaded multiple servlet Jar files.
2. whether the classes and classpath given in web.xml are correct.
Thanks, my problem is solved! Actually I was using Tomcat 10, so I had to use Jakarta servlet instead of javax servlet.
Great. Thanks for the information Ayush.
Ravi, I am trying to create a website for my school where they have to log in to their account and the screen will be based on whether they are a teacher or a student. It is a sort of communications app where teachers can see the given homeworks for the class, to maximizze efficiency. How can I make it so that they have to sign up and put in a username ? Is there any posibility that I can make this in notepad++ or should i use scriptcase for efficiency?
Hi Damian,
I believe scriptcase is PHP based development platform. Depending on the language you are comfortable with, choose one.
The above application is in Java. It explains how a role-based application is built. It’s a basic one. You can add additional features as per the requirement for each role.
PHP example – https://krazytech.com/programs/complete-login-and-registration-application-using-php-and-mysql
thank you
by that is great but I want to ask whether there is an other way to do it using javafx
Yes definitely.