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.

My question is User login not access admin page which condition i apply
Hi Danish,
If I get your question right, to prevent anyone else accessing the User page, the following code will do the job.
< % //In case, if User session is not set, redirect to Login page. if((request.getSession(false).getAttribute("User")== null) ) { %>Sir, can the same code been use in eclipse jee project
Yes. This example is implemented in Eclipse.
sir, i have got error in the code so i send all mine code can you please check it out
This is a tested code. Copy it as is. It should work. You can go through the video as well.
good job. Thank you sooooo much. Very helpful :))
You are welcome Zahra!
Thank you, what if i want to use sql server instead of mysql?
Its simple. Just modify DBConnection.java.
The following 2 lines.
url = “jdbc:mysql://localhost:3306/customers”;
Class.forName(“com.mysql.jdbc.Driver”);
Hello, I’m using your code, thank you!
But I would like to ask how to replace the “Invalid credentials” to an alert message or popup message. So when the user entered wrong data, the popup message will come up instead of adding “invalid credentials” to the form.
Also when I try to run it, once i pass the loginservlet, it doesn’t load the CSS, Images, and other href links when I’m in welcome page already. What should I do?
Copy the CSS tag from the Login.jsp to individual JSPs wherever you want.
You are welcome and Thanks for the comment.
You can do that using javascript. Replace the message with what you want to display.
Why you used session.setAttribute()?what is the use of setting the session id when not used..
Hi Surya,
Good question. Yes. We must use it. It was missed in the code. I have added it in each JSP. You can recompile your code and verify this.
< % //In case, if Admin session is not set, redirect to Login page if((request.getSession(false).getAttribute("Admin")== null) ) { %>
< %} %>
What if i go directly to this link example/user or example/user/user.jsp, how will I know if a session is ongoing and/or the role is correct? thank you and kudos
Hi Ian,
Sorry. The session validation was missed in the code. We must validate if the session is set for each user role. The condition must be added for each user role. You can recompile your code and verify if you still see this issue. Thanks for the catch and comment
if((request.getSession(false).getAttribute(“Admin”)== null) )
Hi Ravi,
Great job, but I think there is a major security flaw in your app? Anyone can bypass login and access any jsp by typing in the following URLs:-
http://localhost:8080/project_name/JSP/Admin.jsphttp://localhost:8080/project_name/JSP/Editor.jsp
http://localhost:8080/project_name/JSP/User.jsp
There is no security in this app?
Andy
Hi Andy,
Good catch. The session validation was missed in the code. We must validate if the session is set for each user role. I have added the condition in 3 JSPs. You can recompile your code and verify if you still see this issue.
< % //In case, if Admin session is not set, redirect to Login page if((request.getSession(false).getAttribute("Admin")== null) ) { %>
< %} %>
Hi
I receive the error below after deployment with embedded Eclipse Tomcat v7, plz help
SEVERE: Allocate exception for servlet LoginServlet
java.lang.ClassNotFoundException: za.co.sapo.servlet.LoginServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
Did you maintain the same folder structure for your project?
Please verify the action element in your form.
I am getting Http 404 status error while running project
But i am getting jsp pages while i am running individually
Hi,
Did you create a dynamic web project? Did you refer to each step given in the video?
The 404 error occurs when the page/file you are accesing doesn’t present with the same name.
Hi, I created a project using both the registration and this login. Being that the respective web.xml files are different how can I make them coexist?
There can be a single web.xml in a project. Merge both the web.xml information into a single one.
So I have to copy and paste the web.xml related to ‘login’ under the web.xml of ‘registration’?
You need to have a common tag under which you need to list all the servlets within and tags.
Comments are closed.