Home »
Java programming language
Design Registration Form using Servlets and Mysql using MVC Pattern
By: Vanka Manikanth, on 12 JAN 2017
Here, we will learn how we can design a registration form using Java Servlets and MySql Database connectivity using MVC pattern?
The given code can be used for form submission using Servlets MVC pattern with MySql Database connectivity.
MVC: MODEL VIEW & CONTROLLER
By using MVC pattern the performance would increase, code can be re-used for any application because here the controller, pojo and service logics are completely separated.
Here we have created three packages in order to make in MVC style. Namely, com.controller.form , com.service.logic, com.pojo.form
Index.jsp
This is a welcome form from where we will take the values for registration from the user.
<%@ 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>REGISTRATION FORM </title>
<style>
#regform{
background-color:green;
}
td{
color:white;
}
p{
text-align:center;
font-size:16pt;
color:green;
}
</style>
</head>
<body>
<form action="controller" method="post">
<p>REGISTRATION FORM</p>
<table cellspacing=10 cellpadding=10 id="regform" align="center">
<tr><td colspan=2 align="justify">USER ID :</td><td><input type="text" name="userid" placeholder="Enter only digits" required="required"></td></tr>
<tr><td colspan=2 align="justify">USERNAME:</td><td> <input type="text" name="username" placeholder="Enter Alphabetics only" required></td></tr>
<tr><td colspan=2 align="justify">PASSWORD:</td><td> <input type="password" name="password" placeholder="Enter your password" required></td></tr>
<tr><td colspan=2 align="justify">EMAIL:</td><td> <input type="email" name="email" placeholder="Enter your email" required></td></tr>
<tr><td colspan=5 align="center"><button type="submit">REGISTER</button></td></tr></table>
</form>
</body>
</html>
Dbconnection.java
This is a class where we creates the Database connection and returns the connection, so that we can avail the returned connection wherever is required.
package com.service.logic;
import java.sql.Connection;
import java.sql.DriverManager;
public class Dbconnection {
public static Connection getConnection(){ //making a static connection,shares to all classes
Connection con=null; // creating connection
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/regform","root","root");
} catch (Exception e) {
//throws an error if at all its unable to create an connection
System.out.println("unable to connect to the database");
}
return con; // we return the connection and we can get the connection wherever needed.
}
}
ControllerServlet.java
This is a controller Servlet which operates the data between the service and pojo class.
package com.controller.form;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pojo.form.Pojo;
import com.service.logic.*;
public class ControllerServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
try {
String userid =req.getParameter("userid");
int id= Integer.parseInt(userid);
String username=req.getParameter("username");
String pass=req.getParameter("password");
String email=req.getParameter("email");
//getting all the values from index.jsp
Pojo pObject = new Pojo();
pObject.setId(id);
pObject.setUsername(username); //setting up the received values from index.jsp to setters and getters
pObject.setPass(pass);
pObject.setEmail(email);
int checkFlag = ServiceLogic.save(pObject); //sending all the values of pojo reference to save method in ServiceLogic
if(checkFlag!=0){
out.print("<h2 align='center'>SuccessFully Registered</h2>"); // if successfully executes save method
out.print("<h2 align='center'> USER ID : "+ id+"</h2>");
out.print("<h2 align='center'> USER NAME : "+username+"</h2>");
out.print("<h2 align='center'> EMAIL : "+ email +"</h2>");
}else{
out.print("<p align='center'>Invalid User Details</p>");
req.getRequestDispatcher("index.jsp").include(req, resp);
}
} catch (Exception e) { // will throw an exception if at all user typed any language constraints.
out.print("<p align='center'>Please enter Valid Details</p>");
req.getRequestDispatcher("index.jsp").include(req, resp);
}
}
}
Pojo.java
This is the class where we use the private variables and implements public setters and getters. Just binding the data received from user.
package com.pojo.form;
public class Pojo {
// set up all the fields received from index.jsp to setters and getters.
private int id;
private String username,pass,email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
ServiceLogic.java
This is where the actual logic exists, here we get the connection from the Dbconnection class and insert the values into database. By separating the logic and we can use the same logic for standalone java application.
package com.service.logic;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.pojo.form.Pojo;
public class ServiceLogic{
public static int save(Pojo pObject){
int flag=0;
try {
Connection con=Dbconnection.getConnection(); //getting the connection method here from dbconnection
PreparedStatement ps = con.prepareStatement("insert into reginfo values(?,?,?,?);");
ps.setInt(1, pObject.getId());
ps.setString(2, pObject.getUsername());//sending up the values received from user to the database table
ps.setString(3, pObject.getPass());
ps.setString(4, pObject.getEmail());
flag=ps.executeUpdate(); //value changes if it is executed
con.close();
} catch (Exception e) {
System.out.println("cannot able to insert");
}
return flag;
}
}
WEB.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FormSubmission</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegistrationForm</servlet-name>
<servlet-class>com.controller.form.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationForm</servlet-name>
<url-pattern>/controller</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Success</servlet-name>
<servlet-class>com.views.form.ViewUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Success</servlet-name>
<url-pattern>/Success</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT