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

This example Java Connection Role-playing Game contains JSP, Java Servlets, session objects and a MySQL database server. You can follow this link to learn how to create databases and tables in MySQL using the open source server software Wamp. This example is an extended version of the Java login page. If you are a beginner and are looking for a simple example of logging in and registering in Java, you can follow the relevant links.

What do you mean, role-playing?

If you want to divide the access level of each user according to his or her role in your application, such as administrator, teacher, student, etc., you need to assign a specific role to each user who logs in, to facilitate the management of large applications. In this example you see 3 roles – administrator, editor and user.

What is a session?

HTTP is a protocol without stateless status, which means that communication between the server and the browser is lost at the end of the transaction. They can’t know who made the request and when it was interrupted. A session helps us maintain a state between the client and the server and can consist of multiple requests and responses between the client and the server. Because HTTP and web servers do not have a stateless status, you use unique information (session ID) to create a session, and this session ID is transferred between the server and the client with every request and response.

It is suggested to read:

Before you start with the actual encoding, you should first look at the list of files and JARs used in this example and how they are placed in the Eclipse IDE (open source Java editor). The blue numbers indicate the order of execution. Then you can watch the video for an explanation.

Fault! The file name is not specified.

Eclipse directory structure for e.g. session- and role-based Java connection

data-medium-file= data-large-file= load=lazy class=wp-image-4308 src= alt=Link directory structure for an example Java connection based on session and role width=272 height=507 data-recal-dims=1/>.

Structure of the Eclipse directory

How do I initiate this request?

The following video explains how and where you can test this application

JSP contains a simple HTML form for entering connection keys. To login to an application, a user must first be registered. Use the registration request to complete the user registration.

<%@ Page language=java contentType=text/html; charset=ISO-8859-1 PageEncoding=ISO-8859-1%>

Top of Form

<%=(request.getAttribute(errMessage) == null)? request.getAttribute(errMessage)%>

Bottom of Form


Java Registration form
Servlet is the controller in the MVC model. It acts as a bridge between the view and the model, i.e. it receives UI claims and sends them to the modeling (business logic) and then to the corresponding operation.

Package com.login.controller ;
Import ;

javax.servlet.servletException import;
javax.servlet.http.HttpServlet import;
javax.servlet.http.HttpServletRequest import;
javax.servlet.http.HttpServletResponse import;
javax.servlet.http.HttpServletResponse import

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

The public class LoginServlet extends HttpServlet {private static last long serialVersionUID =

public LoginServlet() {

protected void doPost(HttpServletRequest request, HttpServletResponse response) launches 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() ;

String userValidate = loginDao.authenticateUser(loginBean)

System.out.println(administration homepage) ;

HttpSession session = request.getSession(); // Session
session.setAttribute(Admin, userName); // Set session attribute
request.setAttribute(userName, userName) ;

request.getRequestDispatcher(/JSP/Admin.jsp).forward(request, reply) ;
anders if(userValidate.equals(Editor_Role))
System.out.println(Editor’s home page) ;

HttpSession session = request.getSession();
request.setAttribute ;

request.getRequestDispatcher(/JSP/Editor.jsp).forward(request, reply) ;
else if(userValidate.equals(user_role))
System.out.println(user’s home page) ;

HttpSession session = request.getSession();
session.setAttribute(username, username);
request.setAttribute(username, username) ;

request.getRequestDispatcher(/JSP/User.jsp).forward(request, response) ;
System.out.println(error = +userValidate) ;
request.setAttribute(error, userValidate) ;

request.getRequestDispatcher(/JSP/Login.jsp).forward(request, reply);
catch (IOException e1)
capture (exception e2)
} //eend of doPost()
JavaBeans are classes that encapsulate many objects in one object. A single object gives easy access to all members of the Bean Class.

Package com.login.bean ;

social class LoginBin

Private line Username; password
Private line ;

public String getUserName() {
returns the username;
public invalid setUserName(String userName) {
this.userName = username;
public string getPassword() {
returns the password;
public invalid setPassword(String password) {
this.password = password;
This class is part of the data access object. The DAO (Data Access Object) is used to abstract and encapsulate all accesses to the data source. The CAD is essentially an object or interface that provides access to main databases or another persistent repository.
In this tutorial, we will compare the username and password entered by the user with the username and password stored in the database during the registration process. Depending on the user’s role, the corresponding 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 ;

social class LoginDao

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

Connection con = zero;
Instruction overview = zero;
Result Set Result Set = zero ;

string userNameDB = ;
string passwordDB = ;
string roleDB = ;

con = DBConnection.createConnection();
statement = con.createStatement();
resultSet = statement.executeQuery(choose username,password,role of users) ;

usernameDB = resultSet.getString(username) ;
passwordDB = resultSet.getString(password) ;
roleDB = resultSet.getString(role) ;

if(Username.equals(UsernameDB) && password.equals(PasswordDB) && roleDB.equals(Admin))provides Admin_Role;other if(Username.equals(UsernameDB) && password.equals(PasswordDB) && roleDB.equals(Editor))gives Editor_Role;other if(Username.equals(UsernameeDB) && Password.equals(PasswordDB) && roleDB.equals(User))gives User_Role;}}catch(SQLException e){e.printStackTrace();} gives invalid user data;}}.

Watch the detailed video demonstrating the implementation of the code by non-professionals.

The following figure shows the MySQL scripts used for this Java login example.

Please note the following:

  • Database name : Customers
  • Name of the table : User

empty MySQL Scripts used in this application

In this application we use a MySQL database. We can use any database server that supports Java. Depending on the database you choose, the correct drivers and connection URLs must be used.

Pay attention: Don’t forget to add a dependent bank for the database server. In our case, it’s a Java Micle connector. The latest version of MySQL 8 needs a small improvement, it works well up to version 8.

Package com.login.util ;

Import java.sql.Connection;
Import java.sql.DriverManager

public class DBC connection {

public static connection createConnection()
connection con = null;
string url = jdbc:mysql://localhost:3306/customers;
string username = root;
string password = root123 ;

catch (ClassNotFoundException e)
con = DriverManager.getConnection(url, username, password);
System.out.println(Message regarding database connection – +con);
catch (SQLException e)
System.out.println(An error has occurred. User/password may be invalid);
return con;


<%@ language=java contentType=text/html; charset=ISO-8859-1 pageEncoding=ISO-8859-1%>

<% //in If the administration session is not installed, please forward to the login page as((request.getSession(false).getAttribute(Admin)==null) ). ) { %><%} %>


Administrative buildings


Welcome <%= Request.getAttribute(Username) %>.




<%@ language=java contentType=text/html; charset=ISO-8859-1 pageEncoding=ISO-8859-1%>

<% //n case, if editor session is not set, redirect to login page if((request.getSession(false).getAttribute(Editor)==null) ). { %><%} %>


Editorial staff


Welcome <%= Request.getAttribute(Username) %>.




<%@ language=java contentType=text/html; charset=ISO-8859-1 pageEncoding=ISO-8859-1%>

<% //n case, if user session is not set, redirect to login page if((request.getSession(false).getAttribute(User)==null) ). { %><%} %>


User’s home address

Welcome <%= Request.getAttribute(Username) %>.


In this application we use a MySQL database. We can use any database server that supports Java. Depending on the database of your choice, you will need to use the appropriate driver and connection URLs.

Pay attention: Don’t forget to add a dependent bank for the database server. In our case, it’s a Java Micle connector.

Package com.login.controller ;

Import; Import
javax.servlet.RequestDispatcher; Import
javax.servlet.ServletException; Import
javax.servlet.http.HttpServletImport RequestDispatcher;
javax.servlet.http.HttpServletImport Response;
javax.servlet.http.HttpServletImport Session ;

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

if(session!=null) // If the session is not null
session.invalidate(); // removes all attributes of the session associated with the request
setAttribute(errMessage, you have successfully logged out);
RequestDispatcher requestDispatcher = request.getRequestDispatcher(/JSP/Login.jsp);
requestDispatcher.forward(request, response);
System.out.println(Logged out);


Web.xml is known as the installation description. It gives an overview of all servlets used in the application. Don’t forget to mention the full name of the servo class.

It has a number of additional parameters, such as the name of the welcome file, which leads to the filename mentioned when downloading this application.
In addition, the Session Timeout setting determines that the session is active for 10 minutes.








You can download the source code via the link below.

Download the source code Full connection and registration of the application with PHP and MySQL

data-medium-file= data-large-file= load=lazy width=317 height=84 data-wpfc-original-src= alt=DownloadNowButton class=wp-image-6412 data-wpfc-original- data-recalc-dims=1/>.

Do you like the manual? Let me know what you think. Your comments are always welcome here.

Related Tags:

how to fax from email outlook,how to fax from computer mac,is safe,how to send a fax from iphone,cocofax,how to fax from printer,how to fax from computer windows 10,faxzero cost,windows fax and scan, reviews,efax free,receive fax to email,efax pricing,google voice fax,afax,how to fax without a fax machine reddit,gotfreefax review,myfax,how to fax without a fax machine for free,fax this bookmarklet,how to fax from home printer,interfax houston,fax cp,fax from home free,j2 fax,best online fax service hipaa compliant,best free online fax service,hellofax reviews,srfax reviews,faxage reviews,is faxzero secure,fax from my phone for free,receive fax on cell phone,verizon fax number,breezy fax app,can i fax using magicjack,how to use a fax machine without a phone line,cheapest way to fax,pay per use fax canada,faxsalad reviews,snapfax pricing,fax service,fax machine,send fax from gmail,send fax online free,send fax from computer,how to send a fax via email,google fax,fax plus,fax zero