PROGRAMS

Login application in Java using MVC and MySQL

This Java login application follows MVC architecture and consists of Java servlets, JSPs. It uses the MySQL database server to refer to the user details. The input fields are validated using javascript.

What is a Model View Controller architecture?

The model (DAO) consists of application data and business rules, and the controller (Servlet) acts as an interface between views and model. It mediates input, converting it to commands for the model or view. A view (JSP) can be any output representation of data, such as a chart or a diagram, generally HTML or JSP page.

Here DAO is the Data Access Object – This part concentrates on business logic and database server connections and operations.

Use any IDE – Integrated development environment to minimize your work. If you haven’t started using any IDE, go get one. You will fall in love with it. I would recommend you to use Eclipse for Java applications. Link to download Eclipse. It is an open-source tool.

This application is explained thoroughly with appropriate comments and tested in Eclipse IDE. Please write comments if you find any difficulty while understanding the application.

Suggested Read:

It is advised to segregate different components in a standard directory structure as shown below. Start your programming with  New Project -> dynamic web application project type.

Eclipse directory structure showing Packages, XML and dependent JARs

Login details are forwarded to LoginServlet from the Login.jsp page. When you click on the Login button the request is forwarded to the page which is mentioned in the action tag of the form so here the request will be forwarded to LoginServlet.java class.

Login.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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
<script> 
function validate()
{ 
  var username = document.form.username.value; 
  var password = document.form.password.value;

  if (username==null || username=="")
  { 
  alert("Username cannot be blank"); 
  return false; 
  }
  else if(password==null || password=="")
  { 
  alert("Password cannot be blank"); 
  return false; 
  } 
}
</script> 
</head>
<body>
 <div style="text-align:center"><h1>Login application in Java using MVC and MySQL </h1> </div>
 <br>
 <form name="form" action="LoginServlet" method="post" onsubmit="return validate()">
  <!-- Do not use table to format fields. As a good practice use CSS -->
  <table align="center">
   <tr>
   <td>Username</td>
   <td><input type="text" name="username" /></td>
   </tr>
   <tr>
   <td>Password</td>
   <td><input type="password" name="password" /></td>
   </tr>
   <tr> <!-- refer to the video to understand request.getAttribute() -->
   <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

package com.mvc.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 com.mvc.bean.LoginBean;
import com.mvc.dao.LoginDao;

public class LoginServlet extends HttpServlet {

 public LoginServlet() // default constructor
 {
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  //Here username and password are the names which I have given in the input box in Login.jsp page. Here I am retrieving the values entered by the user and keeping in instance variables for further use.

  String userName = request.getParameter("username");
  String password = request.getParameter("password");

  LoginBean loginBean = new LoginBean(); //creating object for LoginBean class, which is a normal java class, contains just setters and getters. Bean classes are efficiently used in java to access user information wherever required in the application.

  loginBean.setUserName(userName); //setting the username and password through the loginBean object then only you can get it in future.
   loginBean.setPassword(password);

  LoginDao loginDao = new LoginDao(); //creating object for LoginDao. This class contains main logic of the application.

  String userValidate = loginDao.authenticateUser(loginBean); //Calling authenticateUser function

  if(userValidate.equals("SUCCESS")) //If function returns success string then user will be rooted to Home page
   {
    request.setAttribute("userName", userName); //with setAttribute() you can define a "key" and value pair so that you can get it in future using getAttribute("key")
    request.getRequestDispatcher("/Home.jsp").forward(request, response);//RequestDispatcher is used to send the control to the invoked page.
   }
   else
   {
    request.setAttribute("errMessage", userValidate); //If authenticateUser() function returnsother than SUCCESS string it will be sent to Login page again. Here the error message returned from function has been stored in a errMessage key.
    request.getRequestDispatcher("/Login.jsp").forward(request, response);//forwarding the request
   }
    }
}

LoginDao.java

package com.mvc.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mvc.bean.LoginBean;
import com.mvc.util.DBConnection;

public class LoginDao {
  public String authenticateUser(LoginBean loginBean)
  {
   String userName = loginBean.getUserName(); //Assign user entered values to temporary variables.
   String password = loginBean.getPassword();

   Connection con = null;
   Statement statement = null;
   ResultSet resultSet = null;

   String userNameDB = "";
   String passwordDB = "";

   try
   {
    con = DBConnection.createConnection(); //Fetch database connection object
    statement = con.createStatement(); //Statement is used to write queries. Read more about it.
    resultSet = statement.executeQuery("select userName,password from users"); //the table name is users and userName,password are columns. Fetching all the records and storing in a resultSet.

    while(resultSet.next()) // Until next row is present otherwise it return false
    {
     userNameDB = resultSet.getString("userName"); //fetch the values present in database
     passwordDB = resultSet.getString("password");

      if(userName.equals(userNameDB) && password.equals(passwordDB))
      {
      return "SUCCESS"; ////If the user entered values are already present in the database, which means user has already registered so return a SUCCESS message.
      }
    }
    catch(SQLException e)
    {
    e.printStackTrace();
    }
    return "Invalid user credentials"; // Return appropriate message in case of failure
   }
  }
}

LoginBean.java
JavaBeans are classes that encapsulate many objects into a single object. This object facilitates to access or set all the members of this class. The bean class contains only setters and getters usually.

package com.mvc.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;
  }
}

The database name is customers and the table name is users. If you take a look at the video

, we are using the MySQL database server that comes as part of WAMP software (works for Windows OS). It is a freeware, just download, install, and use it. As an alternative, you can download the MySQL server from the official website. You can use any other database server also.
Script to create users table

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 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.mvc.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"; //MySQL URL and followed by the database name
  String username = "root"; //MySQL username
  String password = "root123"; //MySQL password  
  try 
  {
   try 
   {
   Class.forName("com.mysql.jdbc.Driver"); //loading mysql driver 
   } 
   catch (ClassNotFoundException e)
   {
   e.printStackTrace();
   } 
   con = DriverManager.getConnection(url, username, password); //attempting to connect to MySQL database
   System.out.println("Printing connection object "+con);
  } 
  catch (Exception e) 
  {
  e.printStackTrace();
  }
  return con; 
 }
}

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.

<?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>LoginMvc</display-name>
 <welcome-file-list>
 <welcome-file>Login.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
  <description></description>
  <display-name>LoginServlet</display-name>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>com.mvc.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.mvc.controller.LogoutServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LogoutServlet</servlet-name>
  <url-pattern>/LogoutServlet</url-pattern>
 </servlet-mapping>
</web-app>

Home.jsp
An example of a user home page after successful log-in.

<%@ 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>Home Page</title>
</head>
<body>
 <center><h2>Home Page</h2></center>
 Welcome <%=request.getAttribute("userName") %> <!-- Refer to the video to understand how this works -->
 <div style="text-align: right"><a href="LogoutServlet">Logout</a></div>
</body>
</html>

LogoutServlet.java
This is an example for logout mechanism. After clicking on logout, the user will be redirected to Login.jsp.

package com.mvc.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("/Login.jsp");
    requestDispatcher.forward(request, response);
    System.out.println("Logged out");
   }
 }
}

Many users were asking for the role-based login application. I have made a post recently for the Session and Role based Java Login example.

Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. A founder of Krazytech. It's been 10+ years since I am publishing articles and enjoying every bit of it. I want to share the knowledge and build a great community with people like you.

Leave a Comment

View Comments

  • List of errors I am dealing with even if I have followed same names and structure!!!!!!

    Type Exception Report

    Message Cannot invoke "java.sql.Connection.createStatement()" because "con" is null

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

    Exception

    java.lang.NullPointerException: Cannot invoke "java.sql.Connection.createStatement()" because "con" is null
    com.mvc.dao.LoginDao.authenticateUser(LoginDao.java:27)
    com.mvc.controller.LoginServlet.doPost(LoginServlet.java:35)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    Note The full stack trace of the root cause is available in the server logs.

    Apache Tomcat/9.0.55

    • Hi Pranshu,

      The error is only with the database connection. What version of MySQL are you using? You may need to change the connection parameter accordingly.

  • Hello,

    Thank you for this. It is very helpful. Quick question. Is there a way that I can check if a user is logged in or not? I have a sign in/register button and once the user logs in, I would like to change that text to their username instead or to put the log out button in its place.

  • Great efforts....can u help me with how to create multiple page after clicking on submit button in login page using json without creating multiple jsp pages. As i am new to JSON. also what is the difference between Dao and DaoImpl class.
    need on urgent basis.

    • You need to write a logic in script to frame a JSON object and read it in servlet. Altogether a different application.

    • Hi,

      The business logic is included in DAO file. Go to LoginDao.java class and add the other table details there.

  • Hi, I'm getting an error. I'm already check my LoginServlet but there's no error.

    HTTP Status 404 – Not Found

    Type Status Report

    Message /LoginMvc/LoginServlet

    Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

1 2 3 17
Share
Published by
Ravi Bandakkanavar

Recent Posts

Everything You Need To Know About Create React App

The configuration of resources can be a time-consuming and difficult operation while creating a React…

3 weeks ago

Causes of CyberCrime and Preventive Measures

          Rapid technological growth and developments have provided vast areas of…

4 weeks ago

How Data Lineage will Improve Business Practices

How often have you thought about changing the way that you store and use data?…

4 weeks ago

10 Dominating Programming Language for Mobile App In 2022

Programming Languages are a set of rules that aid in transforming a concept into a…

1 month ago

What is Serverless Edge Computing? Features | Benefits

Serverless edge computing is a new technology with a lot of promise, but it can…

1 month ago

Are Your Accounts Protected Against Cyberattacks?

Do any of your passwords include personal names, date of birth, or pet names? If…

2 months ago