Java Registration Page using Servlet MySQL MVC

By | August 2, 2016

This post explains a simple registration application in Java using Servlet, MySQL, MVC architecture. This Java registration page uses Model View Controller (MVC) design pattern. Let us understand what is MVC and how this should be used while developing any application.

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

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

Model View Controller design pattern implementation in Java

Model View Controller Architecture

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

Eclipse directory structure for Java Registration using JSP Servlet database

Eclipse directory structure for Java Registration using JSP Servlet database

 

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

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register</title>
</head>
<body>
<form name="form1" action="RegisterServlet" method="post">
<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>

 

Java Registration Page

Java Registration Page using MVC

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 {
 private static final long serialVersionUID = 1L;

 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);
 }
 }

}

 

Just 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 successful message.

 

Data Access Object – It mainly contains business logic with database connections and operations.
Here the RegisterDao.java page makes a connection with Database layer and inserts user details in to 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.
 }
}
CeateTable SQL script

CeateTable SQL script

 

Users SQLTable structure

Users Table structure

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

We are going to use MySQL database driver here. The URL format and driver name going to be different for different databases.

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/ravi";
 String username = "root";
 String password = "root";
 
 try 
 {
 try 
 {
 Class.forName("com.mysql.jdbc.Driver");
 } 
 catch (ClassNotFoundException e)
 {
 e.printStackTrace();
 }
  con = DriverManager.getConnection(url, username, password);
 } 
 catch (Exception e) 
 {
 e.printStackTrace();
 }
 return con; 
 }
}
//this file is known as deployment descriptor. It describes the implementation of this application. You need to mention fully qualified path for Servlet here.

&amp;amp;lt;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"&amp;amp;gt;
 &amp;amp;lt;display-name&amp;amp;gt;RegistrationMVC&amp;amp;lt;/display-name&amp;amp;gt;
 &amp;amp;lt;welcome-file-list&amp;amp;gt;
 &amp;amp;lt;welcome-file&amp;amp;gt;Register.jsp&amp;amp;lt;/welcome-file&amp;amp;gt;
 &amp;amp;lt;/welcome-file-list&amp;amp;gt;
 &amp;amp;lt;servlet&amp;amp;gt;
 &amp;amp;lt;description&amp;amp;gt;&amp;amp;lt;/description&amp;amp;gt;
 &amp;amp;lt;display-name&amp;amp;gt;RegisterServlet&amp;amp;lt;/display-name&amp;amp;gt;
 &amp;amp;lt;servlet-name&amp;amp;gt;RegisterServlet&amp;amp;lt;/servlet-name&amp;amp;gt;
 &amp;amp;lt;servlet-class&amp;amp;gt;com.mvc.controller.RegisterServlet&amp;amp;lt;/servlet-class&amp;amp;gt;
 &amp;amp;lt;/servlet&amp;amp;gt;
 &amp;amp;lt;servlet-mapping&amp;amp;gt;
 &amp;amp;lt;servlet-name&amp;amp;gt;RegisterServlet&amp;amp;lt;/servlet-name&amp;amp;gt;
 &amp;amp;lt;url-pattern&amp;amp;gt;/RegisterServlet&amp;amp;lt;/url-pattern&amp;amp;gt;
 &amp;amp;lt;/servlet-mapping&amp;amp;gt;
&amp;amp;lt;/web-app&amp;amp;gt;
Registration Home Page

Registration Home Page

.

Please Share: Tweet about this on TwitterShare on FacebookShare on Google+Share on RedditPin on PinterestShare on LinkedInDigg thisShare on StumbleUponShare on TumblrBuffer this pageShare on VKEmail this to someone

19 thoughts on “Java Registration Page using Servlet MySQL MVC

  1. asd

    Pls tell me how can i set up local database on my pc and can use it with eclipse.

    Reply
  2. sahil

    bro! I am getting this error.

    HTTP Status 500 –

    type Exception report

    message

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception
    java.lang.NullPointerException
    com.mvc.dao.RegisterDao.registerUser(RegisterDao.java:20)
    com.mvc.controller.RegisterServlet.doPost(RegisterServlet.java:34)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    note The full stack trace of the root cause is available in the Apache Tomcat/8.0.8.5.4 logs.

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Sahil,

      At what point did you get this error ?

      Please cross verify the RegisterDao.java class and the method calling in your Servlet code.

      Reply
  3. vikas

    Hi sir,

    Could you please tell me how to retrieve values from database.my requirement is after registering i have to fetch that data from database and i have show that details in edit page.where admin can edit details and update the profile.please help me out
    Thanks in advance sir.

    Reply
  4. vikas

    Sir,
    could you please post code for uploading multiple files using jsp and servlet .iam following MVC pattern.my problem is i have one upload resume field in register page and one more extra documents field for uploading multiple files like passport etc..please help me out i’m struggling fro 2 days.

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Vikas,

      To upload multiple files using MVC would be difficult.
      I think you have to use different input/submit buttons to upload multiple documents. You should upload each one individually.

      Reply
      1. vikas

        sir,
        my requirement is like resume upload in registration form.Admin can upload multiple documents in that field..could u send me any link related to that kind of requirement using jsp and servlet.

        Reply
  5. vikas

    sir,
    could you please explain the servlet flow through pictorial way.iam a beginner could you please help me out.

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Vikas,

      I am here to help you.
      If you go through first image, it explains most of the RegisterServlet flow and also if you refer to my comments within servlet code you will understand the flow.

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

      Even Java Login page is also similar to this. You can learn it in the following post.
      http://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern

      Let me know if you have further doubts.

      Reply
      1. vikas

        Thank you so much for helping me, this is one of the best blog for beginners like me.once again thanks a lot.

        Reply
  6. omer

    i try to execute this code but i get “http 500 status error java.lang.NullPointerException ” what i can do to solve this problem … i hope to help me .. and thanks a lot

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Omer,

      I am here to help you. Could you please tell me on what page you are getting this error.
      Where did you try to execute this code ?
      Are you able to see Register.jsp page ?

      Reply
      1. omer

        thanks ms.ravi i solved this problem .. the error it was in the mysql driver . it’s should be with web content file .. and thanks again for help :)

        Reply

Leave a Reply

Your email address will not be published. Required fields are marked *