PROGRAMS

Java Registration Form using Servlet MySQL MVC

This post explains Registration application in Java using Servlet, JSP, and MySQL database server. This Java registration form follows Model View Controller (MVC) architecture. Let us understand what is MVC and how this should be used while developing any application.

For Login application in java, refer to the post Login application in Java using MVC

The Model View Controller (MVC) architecture can be best explained with the help of the following diagram.

Model View Controller Architecture

We are making use of Eclipse Integrated development environment(IDE) for this Java Registration Application. To follow the basic coding standards, I have created my folder structure as shown in the following diagram.

The eclipse directory structure for the Java Registration application 

Suggested Read:

Any Registration or Login application always begins with views. It can be a page in HTML, JSP, PHP, VB or any other language. Our Java Registration application begins with Register.jsp and from Register.jsp we will call RegisterServlet.java class.

 

Register.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>Register</title>
<script> 
function validate()
{ 
  var fullname = document.form.fullname.value;
  var email = document.form.email.value;
  var username = document.form.username.value; 
  var password = document.form.password.value;
  var conpassword= document.form.conpassword.value;
  
  if (fullname==null || fullname=="")
  { 
  alert("Full Name can't be blank"); 
  return false; 
  }
  else if (email==null || email=="")
  { 
  alert("Email can't be blank"); 
  return false; 
  }
  else if (username==null || username=="")
  { 
  alert("Username can't be blank"); 
  return false; 
  }
  else if(password.length<6)
  { 
  alert("Password must be at least 6 characters long."); 
  return false; 
  } 
  else if (password!=conpassword)
  { 
  alert("Confirm Password should match with the Password"); 
  return false; 
  } 
 } 
</script> 
</head>
<body>
<center><h2>Java Registration application using MVC and MySQL </h2></center>
 <form name="form" action="RegisterServlet" method="post" onsubmit="return validate()">
  <table align="center">
   <tr>
   <td>Full Name</td>
   <td><input type="text" name="fullname" /></td>
   </tr>
   <tr>
   <td>Email</td>
   <td><input type="text" name="email" /></td>
   </tr>
   <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>
   <td>Confirm Password</td>
   <td><input type="password" name="conpassword" /></td>
   </tr>
   <tr>
   <td><%=(request.getAttribute("errMessage") == null) ? ""
   : request.getAttribute("errMessage")%></td>
   </tr>
   <tr>
   <td></td>
   <td><input type="submit" value="Register"></input><input
   type="reset" value="Reset"></input></td>
   </tr>
  </table>
 </form>
</body>
</html>
Registration Form

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

public class RegisterServlet extends HttpServlet {
 
  public RegisterServlet() {
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //Copying all the input parameters in to local variables
   String fullName = request.getParameter("fullname");
   String email = request.getParameter("email");
   String userName = request.getParameter("username");
   String password = request.getParameter("password");
   
   RegisterBean registerBean = new RegisterBean();
  //Using Java Beans - An easiest way to play with group of related data
   registerBean.setFullName(fullName);
   registerBean.setEmail(email);
   registerBean.setUserName(userName);
   registerBean.setPassword(password); 
   
   RegisterDao registerDao = new RegisterDao();
   
  //The core Logic of the Registration application is present here. We are going to insert user data in to the database.
   String userRegistered = registerDao.registerUser(registerBean);
   
   if(userRegistered.equals("SUCCESS"))   //On success, you can display a message to user on Home page
   {
   request.getRequestDispatcher("/Home.jsp").forward(request, response);
   }
   else   //On Failure, display a meaningful message to the User.
   {
   request.setAttribute("errMessage", userRegistered);
   request.getRequestDispatcher("/Register.jsp").forward(request, response);
   }
  }
}

To summarize RegisterServlet.java flow :
1. Assign all the inputs(user details) to local variables.
2. Call RegisterBean.java to set all the user details using java setters.
3. Next, go to RegisterDao.java where you are just going to insert user details into the database.
4. Once it is successful, you are displaying a successful message.

RegisterDao.java

Data Access Object – It focuses on business logic with database connections and operations.
Here the RegisterDao.java code makes a connection with the Database layer and inserts user details into the database.

package com.mvc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mvc.bean.RegisterBean;
import com.mvc.util.DBConnection;

public class RegisterDao { 
  public String registerUser(RegisterBean registerBean)
  {
   String fullName = registerBean.getFullName();
   String email = registerBean.getEmail();
   String userName = registerBean.getUserName();
   String password = registerBean.getPassword();
   
   Connection con = null;
   PreparedStatement preparedStatement = null;   
   try
   {
    con = DBConnection.createConnection();
    String query = "insert into users(SlNo,fullName,Email,userName,password) values (NULL,?,?,?,?)"; //Insert user details into the table 'USERS'
    preparedStatement = con.prepareStatement(query); //Making use of prepared statements here to insert bunch of data
    preparedStatement.setString(1, fullName);
    preparedStatement.setString(2, email);
    preparedStatement.setString(3, userName);
    preparedStatement.setString(4, password);
    
    int i= preparedStatement.executeUpdate();
    
    if (i!=0)  //Just to ensure data has been inserted into the database
    return "SUCCESS"; 
   }
   catch(SQLException e)
   {
   e.printStackTrace();
   }   
   return "Oops.. Something went wrong there..!";  // On failure, send a message from here.
  }
}

MySQL script to create users table
The structure of users table

RegisterBean.java
JavaBeans are classes that encapsulate many objects into a single object (the bean). A JavaBean property is a named feature that can be accessed by the user of the object. Here the RegisterBean encapsulates registration properties fullName, email, userName, password. To set or access individual properties, set and get functions have been implemented.

package com.mvc.bean;

public class RegisterBean {

 private String fullName;
 private String email;
 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;
 }
 public void setFullName(String fullName) {
 this.fullName = fullName;
 }
 public String getFullName() {
 return fullName;
 }
 public void setEmail(String email) {
 this.email = email;
 }
 public String getEmail() {
 return email;
 }
}
DBConnection.java
We are making use of MySQL database server in this application. The URL format and driver name going to be different for different database servers.
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 followed by the database name
     String username = "root"; //MySQL username
     String password = "root123"; //MySQL password
     System.out.println("In DBConnection.java class ");
      
     try
     {
         try
         {
            Class.forName("com.mysql.jdbc.Driver"); //loading MySQL drivers. This differs for database servers 
         } 
         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 deployment descriptor. It declares which Servlets exist and which URLs they handle. You need to mention fully qualified path for Servlet here.

<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>RegistrationMVC</display-name>
 <welcome-file-list>
 <welcome-file>Register.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <description></description>
 <display-name>RegisterServlet</display-name>
 <servlet-name>RegisterServlet</servlet-name>
 <servlet-class>com.mvc.controller.RegisterServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>RegisterServlet</servlet-name>
 <url-pattern>/RegisterServlet</url-pattern>
 </servlet-mapping>
</web-app>

Home.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>
<title>Home Page</title>
</head>
<body>
 <center><h2>Home Page</h2></center>
 <b>User Registration Successful</b>
 <br></br>
 <b>Please <a href="https://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern">log-in</a> to continue.</b>
  
</body>
</html>
Home Page

The code base can be downloaded from here.

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

  • Hello Ravi! The project is downloaded and imported correctly but I am not able to connect through the database. Is there any other thing that I need to download in my system. Like the first page Registration page in opening and after that it is not going anywhere. Please help me with this.

  • Thank you for the tutorial. I have try the tutorial but the problem is why the data do not insert into the database?

    • Hi,
      Do you see any errors after registration? You can put some logs (sys out statements) after the data insertion into the database and check.

      • I am also facing the issue with web.xml, in display-name and description tag. It says invalid name for both the tags. While connection DB I get : "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."

        • Hi,

          Your problem is with URL mapping. Can you check on these 2 values? Make sure they ar exactly same as how you have named them.

          servlet-name and url-pattern

          RegisterServlet
          /RegisterServlet

          If this doesn't work then let me know.

  • Hi Ravi - Great work and thanks! I keep getting "Scripting elements are disallowed here" for this line of code which is in the register.jsp file

    I am using Netbeans. Any idea how to resolve? Thank you

    • Hello,

      Thanks for the comments.
      The Register.jsp has JavaScript validations for the form elements. That’s why you are seeing scripting related error. You need to enable the scripting module and popups. Are you using the inbuilt netbeans browser?

  • Hey, i am keep encountering this message "Oops.. Something went wrong there..!" where i already checked my directory my dbname,password but the records are not inserted

  • Thanks Sir! can you please give also the tuorial for change password as well as forget password
    in MVC model

    • Hi Jofrey,

      Sure, we can do that.
      Forgot password is usally part of Login application and update password is for logged-in users.

      For the forgot password feature, the password should be retrieved from the users table based on the username/email.
      For the update password feature, the password should be updated in the users table based on the username/email.

1 2 3 18
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