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 questions is I login success , but do not back to login.jsp page
Means login session user not back to login.jsp page which condition use.
I am getting java.lang.NullPointerException error
HELP ME!!!!!
Hi Aniruddha,
Could you please tell me when did you see this error?
Hope you are trying with the same code as given.
Hey dude it is working :).
You should have use switch case and break in LogIN.java Servlet
” DaoImpl dao=new DaoImpl();
try
{
String userValidate = dao.authenticUser(usr);
switch (userValidate) {
case “Employee_Role”:
{
System.out.println(“Employee”);
HttpSession session = request.getSession(); //Creating a session
session.setAttribute(“Employee”, email); //setting session attribute
request.setAttribute(“email”, email);
RequestDispatcher rd=request.getRequestDispatcher(“./Employee.jsp”);
rd.forward(request,response);
break;
}
case “User_Role”:
{
System.out.println(“User”);
HttpSession session = request.getSession(); //Creating a session
session.setAttribute(“User”, email); //setting session attribute
request.setAttribute(“email”, email);
RequestDispatcher rd=request.getRequestDispatcher(“./User.jsp”);
rd.forward(request,response);
break;
}
default:
{
System.out.println(“Error message = “+userValidate);
request.setAttribute(“errMessage”, userValidate);
RequestDispatcher rd=request.getRequestDispatcher(“./Login.jsp”);
rd.forward(request, response);
break;
}
}
}
”
If else also works but it is better to use switch case and break.
Yes. Both work.
In before it wasn’t working in login.
When I click Login button it shows null pointer exception but now it’s gone.
I did remove lot of mistake in the code.
Do you mean there are mistakes in this code?
The video explains the end to end execution of the code which contains the same code.
great work. i was wondering are you trying to get an access to an xml file? thanks
Thank you Hanane.
Answer – Nope. It gets generated for servlets and you need to modify it as per the servlet path and your requirements.
Thank you Ravi for your answer. So can i change it to read xml file using rbca? if so can you tell me where i could make changes. it would be really nice.
I want to understand your requirement. Do you want to make your web.xml read-only? the file permission?
Ravi I tried using your code but it always give me an error : Error message = Invalid user credentials .Although I am using the correct credentials for the login process.
Hi Ferry,
This is strange.
Did you verify the user details in your database? Make sure your role is also matching along with the user details.
One of the following conditions must be satisfied in order to log-in successfully.
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";
You can also go through the video https://youtu.be/swdx5g0X1hk to understand the flow.
Already fixed the problem. Thanks for the help!!
Hi Ferry,
That’s great.
Could you please let others know what was the issue and how were you able to resolve it?
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!
Hi Martijn,
You are welcome.
You might have changed the role in LoginServlet.java and LoginDao.java. You should also change it in the database table.
https://krazytech.com/programs/session-role-based-java-login-example#jp-carousel-4319
Let me know if you face any difficulties.
hi, could not deploy it on tomcat server even after adding jar file
Ankush,
Did you try to run on Tomcat integrated with Eclipse?
Refer the video for better understanding – https://youtu.be/swdx5g0X1hk
something is wrong with the code…
connected with database but olways show err message with user name. how is this possiible
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.
Rahul,
Can you go through the video before concluding it is wrong.
Can I call html page rather than jsp
Hi,
Of course, you can use an HTML.
Only drawback is you will not be able to display error message using JSP tag.
how can i catch the username from session in HTML file?
You will not be able to do that unless you use a JSP page.
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/LoginServletCan 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, I followed your each step. The access login path is:
http://localhost:8080/Sample/But when I enter the username and password, I am redirected to this path:
http://localhost:8080/Sample/LoginServletwhere I am getting this error
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
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?
I am getting error in initiating the servlet. I am uisng tomcat9 server
Yes. It is not able to locate your servlet. In the action just specify LoginServlet as shown in the link https://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.
good job.very helpful
You are welcome.
Comments are closed.