How to create registration page using JSP, Servlet and MYSQL

Create a registration page using JSP, Servlet, and MYSQL. Now we have enough to set up all the basic things to develop a web application in java. In this tutorial let’s see

Registration page using JSP, Servlet and MYSQL.

  • Design registration page using JSP.
  • Create a Database and table in MYSQL workbench.
  • Database connectivity in java using JDBC MYSQL.

Design registration page

Create registration.jsp under the JSP folder and include the header.jsp and footer as we did in past tutorials.

registration.jsp

<%@page import="com.javawebapp.utility.ServletUtility"%>
<%@ 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>UserRegistration</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

 <script>
 $( function() {
      $( "#datepicker" ).datepicker({
      	dateFormat : 'mm/dd/yy',
      	changeMonth: true,
        changeYear: true
      });
    } );
  </script>
</head>
<body>
<%@ include file="header.jsp"%>
  <main class="login-form">
  <div class="cotainer">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card">
          <div class="card-header">
            User Registration
            
          </div>
            <%=ServletUtility.getSuccessMessage(request)%>
            <%=ServletUtility.getErrorMessage(request)%>
          <div class="card-body">

            <form action="/JavaWebApp/RegistrationCTL" method="post">

              <input type="hidden" name="uri" value=""> <input
                type="hidden" name="id" value=""> <input
                type="hidden" name="createdBy" value="">
              <input type="hidden" name="modifiedBy"
                value=""> <input type="hidden"
                name="createdDatetime"
                value="">
              <input type="hidden" name="modifiedDatetime"
                value="">

              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">First Name<font color="red"></font></label>
                <div class="col-md-6">
                  <input type="text"   class="form-control" placeholder="Enter First Name"
                    name="firstName" value="" >
                    <font  color="red"></font>
                </div>
              </div>
              
              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Last Name<font color="red"></font></label>
                <div class="col-md-6">
                  <input type="text"   class="form-control" placeholder="Enter Last Name"
                    name="lastName" value="" >
                    <font  color="red"></font>
                </div>
              </div>

              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Login Id<font color="red"></font></label>
                <div class="col-md-6">
                  <input type="text" id="email_address"  class="form-control" placeholder="Enter Login Id"
                    name="login" value="" >
                    <font  color="red"></font>
                </div>
              </div>
              
              
              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Password<font color="red"></font></label>
                <div class="col-md-6">
                  <input type="password" id="email_address"  class="form-control" placeholder="Enter password"
                    name="password" value="" >
                    <font  color="red"></font>
                </div>
              </div>

              
              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Date Of Birth<font color="red"></font></label>
                <div class="col-md-6">
                  <input type="text"  id="datepicker" class="form-control" placeholder="Enter Date Of Birth"
                    name="dob" value="" >
                    <font  color="red"></font>
                </div>
              </div>
              
              
              
              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Mobile No.<font color="red"></font></label>
                <div class="col-md-6">
                  <input type="text" id="email_address"  class="form-control" placeholder="Enter Mobile No"
                    name="mobile" value="" >
                    <font  color="red"></font>
                </div>
              </div>

              <div class="col-md-6 offset-md-4">
                <input type="submit" class="btn btn-primary" name="operation" value="Register">
                
              </div>
            </form>
          </div>

        </div>
      </div>
    </div>
  </div>
  </main>
  <div style="margin-top: 120px">
    <%@ include file="footer.jsp"%>
  </div>
</body>
</html>

Setup Database in MYSQL

Create Database

CREATE SCHEMA `javawebapp` ;

Create user table

CREATE TABLE `javawebapp`.`user` (
  `id` INT NOT NULL,
  `fname` VARCHAR(45) NULL,
  `lname` VARCHAR(45) NULL,
  `login` VARCHAR(45) NULL,
  `password` VARCHAR(45) NULL,
  `dob` DATE NULL,
  `mobile` VARCHAR(45) NULL,
  PRIMARY KEY (`id`));

Create a bean class under the bean package

Bean classes are used to set and get the value. In other words, you can say these are getter and setter classes for the attributes.

Userbean.java

package com.javawebapp.beans;

import java.util.Date;

public class UserBeans {

  private String firstName;
  private String lastName;
  private String login;
  private String password;
  private Date dob;
  private String mobileNo;
  private long id;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  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 getLogin() {
    return login;
  }

  public void setLogin(String login) {
    this.login = login;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public Date getDob() {
    return dob;
  }

  public void setDob(Date dob) {
    this.dob = dob;
  }

  public String getMobileNo() {
    return mobileNo;
  }

  public void setMobileNo(String mobileNo) {
    this.mobileNo = mobileNo;
  }

}

Create a User model under the model package.

UserModel will used to contains all the method related database transactions for users. Like Insert, Delete, Update. In this code, we add only a method to register users and going to make update the same class for upcoming tutorials related to user activity.

UserModel.java

In this UserModel class, we are going to use JDBC data sources. If you are not following this tutorial from start will recommend you to check the JDBCDatasource tutorial.

package com.javawebapp.model;

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

import com.javawebapp.beans.UserBeans;
import com.javawebapp.utility.JDBCDataSource;

import jdk.nashorn.internal.ir.WhileNode;


public class UserModel {
  
  public static long nextPk() {
    long pk = 0;
    Connection conn;
    try {
      conn = JDBCDataSource.getConnection();
      PreparedStatement stmt = conn.prepareStatement("select Max(id) from user");
      ResultSet rs = stmt.executeQuery();
      while(rs.next()){
        pk = rs.getLong(1);
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return pk+1;
    
  }
  
  
  public static long addUser(UserBeans user) {
    int i = 0;
    try {
      Connection conn = JDBCDataSource.getConnection();
      PreparedStatement stmt = conn.prepareStatement("insert into user values(?,?,?,?,?,?,?)");
      stmt.setLong(1, nextPk());
      stmt.setString(2 , user.getFirstName() );
      stmt.setString(3 , user.getLastName() );
      stmt.setString(4 , user.getLogin() );
      stmt.setString(5 , user.getPassword() );
      stmt.setDate(6 , new java.sql.Date(user.getDob().getTime()) );
      stmt.setString(7 , user.getMobileNo() );
        i = 	stmt.executeUpdate();
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
    
    return i;
  }

}

Create a servlet under the controller package

This RegistrationCTL class is a servlet that will get the request to perform the operation and send the response to view(registration.jsp).

RegisterationCTL.java

package com.javawebapp.Controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javawebapp.beans.UserBeans;
import com.javawebapp.model.UserModel;
import com.javawebapp.utility.DataUtility;
import com.javawebapp.utility.ServletUtility;

/**
 * Servlet implementation class RegistrationCTL
 */
@WebServlet(name = "RegistrationCTL", urlPatterns = {"/RegistrationCTL"})
public class RegistrationCTL extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationCTL() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    //ServletUtility.forward("jsp/registration.jsp", request, response);
    request.getRequestDispatcher("jsp/registration.jsp").forward(request, response);
    //response.sendRedirect("jsp/registration.jsp");
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    
    UserBeans user = new UserBeans();
    user.setFirstName(request.getParameter("firstName"));
    user.setLastName(request.getParameter("lastName"));
    user.setLogin(request.getParameter("login"));
    user.setPassword(request.getParameter("password"));
    user.setDob(DataUtility.getDate(request.getParameter("dob")));
    user.setMobileNo(request.getParameter("mobile"));
    
    long i = UserModel.addUser(user);
    if(i>0) {
      ServletUtility.setSuccessMessage("User register sucessfully", request);
      
    }else {
      ServletUtility.setErrorMessage("Not insterted", request);
    }
    request.getRequestDispatcher("jsp/registration.jsp").forward(request, response);
  }

}