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.

hey,
m getting an error 404 not found
what could the problem be after following everything according to your code
Did you create Java classes with the same names? Also the package names and web.xml
i created the exact copy of your project with same file names and data base names and fields ….. but still iam encountered with an error (error 404: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.)
please help me out in this …. i even referred the stack overflow link you provided but it finds me unhelpful… please elaborate
Logesh,
404 means the resource is not available. Here the resource is your servlet path. You need to verify the servlet name, method type, XML, directory structure. This is a working example. You can go through the video and try making a new project.
I get one error >>>> Unknown column ‘roll’ in ‘field list’.
Same code i have written.
Sir, code runs successfully…..Sorry for asking the easier query.
Good to hear that Shubham. Happy coding!
hi
What i must modify to do it with hibernate
Hi Nourhen,
I hope that I have already replied to your query.
how i can do this with the framework hibernate ?
Hi Nourhen,
Many things need to be modified in order to implement hibernate. I would suggest you to go through hibernate examples first.
how i can do this with the framework hibernate ?
Hi Ravi, I want to use this code with Postgres SQL. can you please tell me what changes should i need to do. I Update DBConnection file with postgres configuration and also updated postgres jar file. But i am getting error Invalid Credential while running this code. Please help
Hi Ravi, I followed your code but not to able to login. Everytime it’s giving me an error Invalid User Credentials!! Please help
Post establishing a DB connection – org.postgresql.jdbc3g.Jdbc3gConnection@92bfa68
Error message = Invalid user credentials
Ishika,
Sorry for the delayed response.
What you are probably missing is registration of the user. In order to log in, the user must be registered. First, complete the registration process then try logging in. as an alternative, you can just enter user’s details in the DB as well.
https://krazytech.com/programs/java-registration-page-using-servlet-mysql-mvc
User details exist in database. I also tried to print user details and its fetch user details from database successfully. But it not redirecting user according to his role. Instead it giving error only. And this case happening with PostgreSQL only. With using MySQL database same logic working very well.
Hey is runing successfully. Actually there was space in my db data. now problem solved :-)
I need to do it with hibernate. Can you suggest me what changes should i need to do? Thanks
Good to know that this is working for you.
Many things need to be changed if you want to implement hibernate for this example. I would suggest you to go through hibernate examples first.
Hi..I follow this tutorial and facing an issue. I entered username and password in login form but it doesn’t allow me to access admin/user page instead it continuously shows Invalid user credentials. Please help!!!
hey you can not understand my question ..
Look user role is login with session after user go user.jsp page , But user click the back than show login page.
Which condion apply on “login.jsp” page the session login user not back login.jsp page
logout compulsary
Hi Danish,
If you don’t want to go back after successful login, you can use the javascript code to disable the browser back button.
Comments are closed.