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

Monday, 19 February 2018

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

Hi, This article will show you how to use JSP, Servlet, and MySQL to create a Java MVC login and registration script. I designed a 3-tier pattern approach in Java once I finish learning JSP and Servlet. The 3-Tier architecture is a software design paradigm in which business processes are represented by logic (Model), presentation layers (View) represent user interface, and the center (Controller) receives requests and responds to them.


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.


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. Or Model can be a POJO that encapsulates controller-specified application data.

  • View – It is responsible for rendering model data, 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 access data.

View part -> Controller -> Business Logic  -> DAO -> DB

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 model class but Model class follows old java object concepts.

Project Directory :-

This is the directory structure for our project, which includes three jar files: mysql-connector-java-5.1.15-bin.jar, jsp-api.jar, and servlet-api.jar. These three jar files are already in the lib folder.

NetBeans IDE Project Directory Structure of Java MVC Login and Register Script Using JSP & Servlet With MySQL

Database / Table

The database used in this tutorial is "db_mvclogin" and the table is "user", so create "db_mvclogin" in your PHPMyAdmin and paste the following SQL code for user table creation.

-- 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 ]

Index.jsp as a login form that takes the username and password to the welcome page for users to access. If the user data are incorrect, a suitable message will be displayed.

method="post" attribute transfer form data to the server as an HTTP POST request. And action="LoginController" attribute indicates the relative URL of the Servlet LoginController file which is responsible for handling the data posted 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

Create LoginController class that is mapped to the URL: LoginController by servlet-mapping tags including that of the child tags servlet-name and url-pattern defined on the web.xml file

This class communicates with the two "LoginBean" and "LoginDao" model classes. The class LoginBean binds the value of the login form fields, set by that object. And LoginDao class contains business logic for authenticator users who access the welcome page including HttpSession.

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

This class encapsulates the data of the login form given by the class LoginController. We define the private variables and we apply the public setters and getters to them.

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

In this class, we established a MySQL database connection and create secure user access login codes to verify the username and password values of the authorized user in the database. If both records are detected, return to the controller the login message, else return the incorrect username and password message.

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"
    }
}


register.jsp

This is our simple registration form that accepts the first name, last name, username, and password of the user.

method="post" attribute send form data to the server as an HTTP POST request. And action=" RegisterController" attribute specifies the relative URL of the Servlet RegisterController file responsible for controlling the posted new user data from that form. 

<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

Create the class RegisterController that is mapped to the URL: RegisterController by servlet-mapping tags including that of the child tags servlet-name and url-pattern defined on the web.xml file

This class communicates between "RegisterBean" and "RegisterDao" with two model classes. The RegisterBean class binds the field's value of the registration form, which is set by its object. And RegisterDao class contains logic for inserting codes to effectively register new user data.

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

This class encapsulates the value of registration form given by the class RegisterController. We define the private variables and we add the public setters and getters to them.

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

This class stores 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"
    }
}

Learn More – How to Send Email After Registration with Activation Link in Java


welcome.java

This is our welcome page that only session login users can access, if the session is empty, the login/index page will redirect it to.

<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

The current authenticated user session is destroyed by the following codes, each user logouts, and redirects to the login/index page instantly.

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

web.xml

<?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