Java MVC Login and Register Script Using JSP & Servlet With MySQL - onlyxcodes

Thursday 23 May 2024

Java MVC Login and Register Script Using JSP & Servlet With MySQL

Hi, In this tutorial I will show you Java MVC Login and Register Script Using JSP and Servlet with MySQL database. 


After I had finished learning Servlet and JSP, I created a 3-tier pattern approach in Java. A software design model known as the 3-Tier architecture uses display layers (View) to represent the user interface, logic (Model) to represent business operations, and a controller at the center to handle requests and provide answers. 


The MVC architecture splits and encapsulates the sections of your applications for simpler maintenance. This tutorial follows the 3-tier pattern and will show you how to construct a better application by using JSP, Servlet, and Java classes.


For easier maintenance, the MVC architecture divides and encapsulates the many parts of our programs. Using JSP, Servlet, and Java classes, I will demonstrate how to create a more robust application in this 3-tier design tutorial.


Java MVC Login and Register Script Using JSP & Servlet With MySQL

What is MVC Architecture in Java?

MVC(Model View Controller) is an architectural design pattern that divides an application into three key logical components: the model, view, and controller;

  • Model – It will be some layer of DAO that gives user request information. The model can be a POJO that encapsulates controller-specified application data.
  • View – It is responsible for rendering model data, and generating new output based on model changes, which can be interpreted by the client's browser.
  • Controllers – Interacting between Model and View components to process all business logic and incoming requests, manipulating data using the Model component, and interacting with Views to render the final result.

DAO (Data Access Object) – This layer contains all class methods or we can say that the DAO class contains actual logic following JDBC logic. That database accesses data.


POJO (Plain Old Java Object) class is created for binding form values to fields. It will put that object in the model. POJO class is not a model class but a Model class follows old Java object concepts.


Database and Table Design

In my PHPMyAdmin, I used "db_mvclogin" named database and within this database, I created a "user" table with five fields.


 -- Database: `db_mvclogin`
--

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `firstname` varchar(12) NOT NULL,
  `lastname` varchar(12) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.jsp ( Login Page )

This is the "index.jsp" page. I have a basic login form with two fields password and username as well as a login button on this page.


Here I have also explained the form tag method and action attribute.


method="post":- This attribute communicates form data to the server using the HTTP POST request. 


action="LoginController":- This property provides the relative URL of the Servlet LoginController file, which manages the information sent from that form.


 <h2>Login</h2>
            
<form method="post" action="LoginController" name="LoginForm" onsubmit="return validate();">
                
    Username    :<input type="text" name="txt_username">
    Password    :<input type="password" name="txt_password">
                
    <input type="submit" name="btn_login" value="Login">
                
    <h3>Your don't have a account? <a href="register.jsp">Register</a></h3>
                
</form>

Login Form:-


Login Form

LoginController.java

The LoginController class that I have built is mapped to the URL "LoginController" through the use of servlet-mapping tags. Additionally, the child tags servlet-name and url-pattern defined in the web.xml file are incorporated.


The two model classes "LoginBean" and "LoginDao" are in communication with this class. 


I have confined the values of the login form fields which are set by the object in the LoginBean class. 


I used business logic in the LoginDao class for authenticator users who use HttpSession to view the welcome page.


 package com.mvc.controller;

import com.mvc.bean.LoginBean;
import com.mvc.dao.LoginDao;

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 LoginController extends HttpServlet 
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        if(request.getParameter("btn_login")!=null) //check button click event not null from login.jsp page button
        {
            String username=request.getParameter("txt_username"); //get textbox name "txt_username"
            String password=request.getParameter("txt_password"); //get textbox name "txt_password"
            
            LoginBean loginBean=new LoginBean(); //this class contain seeting up all received values from index.jsp page to setter and getter method for application require effectively 
            
            loginBean.setUsername(username); //set username through loginBean object
            loginBean.setPassword(password); //set password through loginBean object
            
            LoginDao loginDao=new LoginDao(); //this class contain main logic to perform function calling and database operation
            
            String authorize=loginDao.authorizeLogin(loginBean); //send loginBean object values into authorizeLogin() function in LoginDao class
            
            if(authorize.equals("SUCCESS LOGIN")) //check calling authorizeLogin() function receive string "SUCCESS LOGIN" message after continue process
            {
                HttpSession session=request.getSession(); //session is created
                session.setAttribute("login",loginBean.getUsername()); //session name is "login" and  store username in "getUsername()" get through loginBean object
                RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp"); //redirect to welcome.jsp page
                rd.forward(request, response);
            }
            else
            {
                request.setAttribute("WrongLoginMsg",authorize); //wrong login error message is "WrongLoginMsg"
                RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); //show error same index.jsp page
                rd.include(request, response);
            }
        }
    }

}

LoginBean.java

The class LoginController provides the login form's data, which I defined as private variables and then applied the public setters and getters performs too.


 package com.mvc.bean;

public class LoginBean 
{
    private String username,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

I built secure user access login codes and connected a MySQL database for this class in order to confirm the authorized user's username and password.


This code delivers the login message to the controller if both records are found; if not, it returns the message with the wrong username and password.


 package com.mvc.dao;

import com.mvc.bean.LoginBean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LoginDao 
{
    public String authorizeLogin(LoginBean loginBean) //create authorizeLogin()function
    {
        String username=loginBean.getUsername(); //get username value through loginBean object and store in temporary variable "username"
        String password=loginBean.getPassword(); //get password value through loginBean object and store in temporary variable "password"
        
        String dbusername="";  //create two variable for use next process
        String dbpassword="";
        
        String url="jdbc:mysql://localhost:3306/db_mvclogin"; //database connection url string
        String uname="root"; //database username
        String pass=""; //database password
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); //load driver
            Connection con=DriverManager.getConnection(url,uname,pass); //create connection
            
            PreparedStatement pstmt=null; //create statement
            
            pstmt=con.prepareStatement("select * from user where username=? and password=?"); //sql select query 
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            ResultSet rs=pstmt.executeQuery(); //execute query and set in Resultset object rs.
             
            while(rs.next())
            {    
                dbusername=rs.getString("username");   //fetchable database record username and password store in this two variable dbusername,dbpassword above created 
                dbpassword=rs.getString("password"); 
                
                if(username.equals(dbusername) && password.equals(dbpassword))  //apply if condition check for fetchable database username and password are match for user input side type in textbox
                {
                    return "SUCCESS LOGIN"; //if valid condition return string "SUCCESS LOGIN" 
                }
            } 
           
            pstmt.close(); //close statement
            
            con.close(); //close connection
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        return "WRONG USERNAME AND PASSWORD"; //if invalid condition return string "WRONG USERNAME AND PASSWORD"
    }
}

Registration Page ( register.jsp )

I've made a registration form for this page that takes in the user table's first and last names, username, and password fields.


I have also described the registration form tag method and action attributes.


method="post":-  This attribute uses an HTTP POST request to communicate form data to the server. 


action=" RegisterController":- The relative URL of the Servlet RegisterController file, which is responsible for managing the newly posted user data from that form, is specified by this attribute.  


 <h2>Register</h2>
            
<form method="post" action="RegisterController" onsubmit="return validate();">
               
    Firstname   <input type="text" name="txt_firstname" id="fname"></br></br>
    Lastname    <input type="text" name="txt_lastname" id="lname"></br></br>
    Username    <input type="text" name="txt_username" id="uname"></br></br>
    Password    <input type="password" name="txt_password" id="password"></br></br>
                
    <input type="submit" name="btn_register" value="Register">
                
    <h3>You have a account? <a href="index.jsp">Login</a></h3>
                
</form>

Registration Form:-


registration form

RegisterController.java

My class, RegisterController, is mapped to the URL RegisterController through the use of servlet-mapping tags, which also include child tags for servlet-name and url-pattern that are defined in the web.xml file. 


Using two model classes, this class enables the communication between "RegisterBean" and "RegisterDao". 


The RegisterDao class has logic for inserting codes to successfully register new user data, and the RegisterBean class binds the registration form's field value, which is set by its object. 


 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 com.mvc.bean.RegisterBean;
import com.mvc.dao.RegisterDao;

public class RegisterController extends HttpServlet 
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        
        if(request.getParameter("btn_register")!=null) //check button click event not null from register.jsp page button
        {
            String firstname=request.getParameter("txt_firstname");
            String lastname=request.getParameter("txt_lastname");
            String username=request.getParameter("txt_username");  //get all textbox name from register.jsp page
            String password=request.getParameter("txt_password");
            
            RegisterBean registerBean=new RegisterBean(); //this class contain  seeting up all received values from register.jsp page to setter and getter method for application require effectively
            
            registerBean.setFirstname(firstname);
            registerBean.setLastname(lastname);
            registerBean.setUsername(username);  //set the all value through registerBean object
            registerBean.setPassword(password);
            
            RegisterDao registerdao=new RegisterDao(); //this class contain main logic to perform function calling and database operation
            
            String registerValidate=registerdao.authorizeRegister(registerBean); //send registerBean object values into authorizeRegister() function in RegisterDao class
            
            if(registerValidate.equals("SUCCESS REGISTER")) //check calling authorizeRegister() function receive "SUCCESS REGISTER" string message after redirect to index.jsp page
            {
                request.setAttribute("RegiseterSuccessMsg",registerValidate); //apply register successfully message "RegiseterSuccessMsg"
                RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); //redirect to index.jsp page
                rd.forward(request, response);
            }
            else
            {
                request.setAttribute("RegisterErrorMsg",registerValidate); // apply register error message "RegiseterErrorMsg"
                RequestDispatcher rd=request.getRequestDispatcher("register.jsp"); //show error same page register.jsp page
                rd.include(request, response);
            }
        }
    }

}

RegisterBean.java

I defined the private variables and attached the public setters and getters methods to them to encapsulate the value of the registration form provided by the class RegisterController in this class.


 package com.mvc.bean;

public class RegisterBean 
{
    private String firstname,lastname,username,password;
    
    public String getFirstname(){
        return firstname;
    }
    public void setFirstname(String firstname){
        this.firstname=firstname;
    }
    public String getLastname(){
        return lastname;
    }
    public void setLastname(String lastname){
        this.lastname=lastname;
    }
    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;
    }
}

RegisterDao.java

In this class, I stored the new user data in the database, which is retrieved directly from Registercontroller by user type and returns the success register message to the controller to the index page.


 package com.mvc.dao;
import com.mvc.bean.RegisterBean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class RegisterDao 
{
    public String authorizeRegister(RegisterBean registerBean) //create authorizeRegister()function
    {
        String firstname=registerBean.getFirstname();
        String lastname=registerBean.getLastname();
        String username=registerBean.getUsername();  //get all value through registerBean object and store in temporary variable
        String password=registerBean.getPassword();
        
        String url="jdbc:mysql://localhost:3306/db_mvclogin"; //database connection url string
        String uname="root"; //database username
        String pass=""; //database password
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); //load driver
            Connection con=DriverManager.getConnection(url,uname,pass); //create connection
            
            PreparedStatement pstmt=null; //create statement
            
            pstmt=con.prepareStatement("insert into user(firstname,lastname,username,password) values(?,?,?,?)"); //sql insert query
            pstmt.setString(1,firstname);
            pstmt.setString(2,lastname);
            pstmt.setString(3,username);
            pstmt.setString(4,password); 
            pstmt.executeUpdate(); //execute query
             
            pstmt.close(); //close statement
            
            con.close(); //close connection
           
            return "SUCCESS REGISTER"; //if valid return string "SUCCESS REGISTER" 
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
            return "FAIL REGISTER"; //if invalid return string "FAIL REGISTER"
    }
}

welcome.java

I have created the welcome page and within this page, only session login users can access it. 


This page will take the user to the index page if they attempt to log in without using the session.


 <center>
 
<h2>
    <%
    if(session.getAttribute("login")==null || session.getAttribute("login")=="") //check if condition for unauthorize user not direct access welcome.jsp page
    {
        response.sendRedirect("index.jsp");
    }
    %>
    
    Welcome, <%=session.getAttribute("login")%> 

</h2>

<h3>
    <a href="logout.jsp">Logout</a>
</h3>

</center>

welcome page

logout.jsp

In this file, I have created the session destroy and logout code.


If login users click on the logout link then this page destroys the session and sends it to the index page.


 <%
    session.invalidate(); //session destroy
    response.sendRedirect("index.jsp"); //after destroy redirect to index.jsp page
%>

web.xml

This is my web.xml file and this file maps the application relative to all URLs that we discussed above.


 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>RegisterController</servlet-name>
        <servlet-class>com.mvc.controller.RegisterController</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LoginController</servlet-name>
        <servlet-class>com.mvc.controller.LoginController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RegisterController</servlet-name>
        <url-pattern>/RegisterController</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LoginController</servlet-name>
        <url-pattern>/LoginController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Download Codes

2 comments:

  1. can i delete folder lib if i use netbeans??? and what is the lib folder function?

    ReplyDelete
    Replies
    1. Put .jar files in lib folder mysql-connect.jar, jsp-api.jar that is use for lib folder

      Delete

Post Bottom Ad