Welcome back friends, this is my continuing post from the previous tutorial, well the previous tutorial we build Login and Register project base on Java MVC codes comes under JSP, Servlet and Java classes to introduce Model (Java Class), View (JSP) and Controller(Servlet). Now we use the same strategies regarding the previous tutorial in this tutorial and we develop project Add, Edit, and Delete based on the structure of Java MVC.
I have clarified all about MVC in my previous tutorial. What is MVC Architecture in Java, POJO, or Model class purpose and DAO class as to how to apply the business logic in this class? If you don't know how it works on Java MVC, read my previous post. Let's begin building a new project.

Technology and Tool
Platfrom Version – Java 8
Editor: NetBeans IDE
Jar files – That project required three jar files. They're mysql-connector-java-5.1.15-bin.jar, jsp-api.jar, and servlet-api.jar.
Copy and paste all the jar files into WEB-INF —>lib folder.

Create 3 packages within the src folder.
com.mvc.bean: It contains the class POJO (Plain Old Java Object). This class protects the variable of entity member by the method getters and setters.
com.mvc.controller: contains the servlets.
com.mvc.dao: It contains class DAO (Data Access Object) logic for the operation of databases.
Database Schema
Go to your PhpMyAdmin to run the following SQL code This is to generate a table in our database. By the way, in this tutorial, the database name we used was called "db_mvcoperation".
CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(15) NOT NULL,
`owner` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
add.jsp
Easy HTML form for inserting records of the person includes two text boxes for entering the name of the person and the owner as a company.
After filling the data and submitting the form, AddController first occurred to be executed attributable to the form action="AddController" which is the relative URL of the servlet file. And HTTP POST request sends the value of fields of the form to the server.
See just before closing the form tag, this page will display an appropriate message if any error occurred.
<form method="post" action="AddController" onsubmit="return validate();">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="txt_name" id="name"></td>
</tr>
<tr>
<td>Owner</td>
<td><input type="text" name="txt_owner" id="owner"></td>
</tr>
<tr>
<td><input type="submit" name="btn_add" value="Add"></td>
</tr>
</table>
<center>
<h3 style="color:red;">
<%
if(request.getAttribute("InsertErrorMsg")!=null)
{
out.println(request.getAttribute("InsertErrorMsg")); //get insert record fail error message from AddController.java
}
%>
</h3>
<h1><a href="index.jsp">Back</a></h1>
</center>
</form>
AddController.java
Create a Servlet file with AddController class name that is mapped to the URL: AddController. And that file gets all the values of the form that users enter.
This class communicates with the AddBean and AddDao model classes. The class AddBean sets the property of form fields to that object. And AddDao class contains logic for JDBC codes to insert new user records into the database table.
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.AddBean;
import com.mvc.dao.AddDao;
public class AddController extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if(request.getParameter("btn_add")!=null) //check button click event not null from add.jsp page after continue
{
String name=request.getParameter("txt_name"); //get textbox name "txt_name"
String owner=request.getParameter("txt_owner"); //get textbox name "txt_owner"
AddBean addBean=new AddBean(); //this class contain setting up all receive values from add.jsp page to seeter and getter method for application require effectively
addBean.setName(name); //set name through addBean object
addBean.setOwner(owner); //set owner through addBean object
AddDao addDao=new AddDao(); //this class contain main logic to perform function calling and database operation
String insertValidate=addDao.checkInsert(addBean); //send addBean object values into checkInsert() function in AddDao class
if(insertValidate.equals("INSERT SUCCESS")) //check calling checkInsert() function receive string "INSERT SUCCESS" after redirect to index.jsp page and display record
{
request.setAttribute("InsertSuccessMsg",insertValidate); //setAttribute value is "InsertSuccessMsg" for insert successfully message
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
else
{
request.setAttribute("InsertErrorMsg",insertValidate); //setAttribute value is "InsertErrorMsg" for insert fail message
RequestDispatcher rd=request.getRequestDispatcher("add.jsp");
rd.include(request, response);
}
}
}
}
AddBean.java
In this class, we define all properties of the form that must be private and implements with the public by methods getters and setters.
package com.mvc.bean;
public class AddBean
{
private String name,owner;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getOwner(){
return owner;
}
public void setOwner(String owner){
this.owner=owner;
}
}
AddDao.java
In this class we create a connection to the MySQL database, apply the SQL insert query to properly insert new user records into the person table. If records are added, return a success message to AddController, otherwise, return the failed message.
package com.mvc.dao;
import com.mvc.bean.AddBean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class AddDao
{
public String checkInsert(AddBean addBean)
{
String name=addBean.getName(); //get name through addBean object and store in temporary variable "name"
String owner=addBean.getOwner(); //get owner through addBean object and store in temporary variable "owner"
String url="jdbc:mysql://localhost:3306/db_mvcoperation"; //database connection url string
String username="root"; //database connection username
String password=""; //database password
try
{
Class.forName("com.mysql.jdbc.Driver"); //load driver
Connection con=DriverManager.getConnection(url,username,password); //create connection
PreparedStatement pstmt=null; //create statement
pstmt=con.prepareStatement("insert into person(name,owner) values(?,?)"); //sql insert query
pstmt.setString(1,name);
pstmt.setString(2,owner);
pstmt.executeUpdate(); //execute query
pstmt.close(); //close statement
con.close(); //close connection
return "INSERT SUCCESS"; //if valid return "INSERT SUCCESS" string
}
catch(Exception e)
{
e.printStackTrace();
}
return "FAIL INSERT"; //if invalid return "FAIL INSERT" string
}
}
edit.jsp
The editing form is as simple as the insert form is. When editing a record, we have to collect selected records from the database and each value in text boxes.
After editing and submitting existing data, EditController first occurred to be executed attributable to the form action="EditController" which is the relative URL of the servlet file. And HTTP POST request sends the new value to the server for form fields.
Note: Exactly close the update button, we create a hidden text box and in this text box, we store specific table ids that can be retrieved. This hidden Id helps in updating existing records.
See just before the form tag is closed if any update error occurred this page will display a suitable message.
<form method="post" action="EditController" onsubmit="return validate();">
<table>
<%
if(request.getParameter("edit_id")!=null) //get edit_id from index.jsp page with href link and check not null after continue
{
int id=Integer.parseInt(request.getParameter("edit_id")); //get edit_id store in "id" variable
String url="jdbc:mysql://localhost:3306/db_mvcoperation"; //database connection url string
String username="root"; //database connection username
String password=""; //database password
try
{
Class.forName("com.mysql.jdbc.Driver"); //load driver
Connection con=DriverManager.getConnection(url,username,password); //create connection
PreparedStatement pstmt=null; //create statement
pstmt=con.prepareStatement("select * from person where id=?"); //sql select query
pstmt.setInt(1,id);
ResultSet rs=pstmt.executeQuery(); //execute query and set in Resultset object rs.
while(rs.next())
{
%>
<tr>
<td>Name</td>
<td><input type="text" name="txt_name" id="name" value="<%=rs.getString("name")%>"></td>
</tr>
<tr>
<td>Owner</td>
<td><input type="text" name="txt_owner" id="owner" value="<%=rs.getString("owner")%>"></td>
</tr>
<tr>
<td><input type="submit" name="btn_edit" value="Update"></td>
</tr>
<input type="hidden" name="hidden_id" value="<%=rs.getInt("id")%>">
<%
}
pstmt.close(); //close statement
con.close(); //close connection
}
catch(Exception e)
{
e.printStackTrace();
}
}
%>
</table>
<center>
<h3 style="color:red;">
<%
if(request.getAttribute("UpdateErrorMsg")!=null)
{
out.print(request.getAttribute("UpdateErrorMsg")); //get update record fail error message from EditController.java
}
%>
</h3>
<h1><a href="index.jsp">Back</a></h1>
</center>
</form>
EditController.java
Create a file for Servlet with the name of the class EditController mapped to the URL: EditController. This class gets all the new values that modify from the user to form.
This class interacts with two EditBean and EditDao model classes. The class EditBean sets the property of the editable fields for the form by that object. And EditDao class includes logic for JDBC codes to update specific user records.
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.EditBean;
import com.mvc.dao.EditDao;
public class EditController extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if(request.getParameter("btn_edit")!=null) //check button click event not null form edit.jsp page after continue
{
String name_up=request.getParameter("txt_name"); //get textbox name "txt_name"
String owner_up=request.getParameter("txt_owner"); //get textbox name "txt_owner"
int hidden_id=Integer.parseInt(request.getParameter("hidden_id")); //get hidden id name "hidden_id"
EditBean editBean=new EditBean(); //this class contain setting up all receive values from edit.jsp page to seeter and getter method for application require effectively
editBean.setName_UP(name_up);
editBean.setOwner_UP(owner_up); //set all value through editBean object
editBean.setHidden_ID(hidden_id);
EditDao editDao=new EditDao(); //this class contain main logic to perform function calling and database operation
String updateValidate=editDao.checkUpdate(editBean); //send editBean object values into checkUpdate() function in EditDao class
if(updateValidate.equals("UPDATE SUCCESS")) //check calling checkUpdate() function receive string "UPDATE SUCCESS" after redirect to index.jsp page and display update record
{
request.setAttribute("UpdateSuccessMsg",updateValidate); //setAttribute value is "UpdateSuccessMsg" for update successfully message
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
else
{
request.setAttribute("UpdateErrorMsg",updateValidate); //setAttribute value is "UpdateErrorMsg" for update fail message
RequestDispatcher rd=request.getRequestDispatcher("edit.jsp");
rd.include(request, response);
}
}
}
}
EditBean.java
In this class, we define properties of update form and all properties must be specified with the public by methods getters and setters to define private and implements.
package com.mvc.bean;
public class EditBean
{
private String name_up,owner_up;
private int hidden_id;
public String getName_UP(){
return name_up;
}
public void setName_UP(String name_up){
this.name_up=name_up;
}
public String getOwner_UP(){
return owner_up;
}
public void setOwner_UP(String owner_up){
this.owner_up=owner_up;
}
public int getHidden_ID(){
return hidden_id;
}
public void setHidden_ID(int hidden_id){
this.hidden_id=hidden_id;
}
}
EditDao.java
This DAO class also contains logic for JDBC codes for updating specific user records. In this class, we set up all settings in the database connection, fire SQL update query if the user types new records then updates existing records that otherwise put old records the same as they are.
After completing the update task we return the message of success of the update to EditController, otherwise, we return the message of failure.
package com.mvc.dao;
import com.mvc.bean.EditBean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class EditDao
{
public String checkUpdate(EditBean editBean)
{
String name_up=editBean.getName_UP();
String owner_up=editBean.getOwner_UP(); //get all value through editBean object and store in temporary variable
int hidden_id=editBean.getHidden_ID();
String url="jdbc:mysql://localhost:3306/db_mvcoperation"; //database connection url string
String username="root"; //database connection username
String password=""; //database password
try
{
Class.forName("com.mysql.jdbc.Driver"); //load driver
Connection con=DriverManager.getConnection(url,username,password); //create connection
PreparedStatement pstmt=null; //create statement
pstmt=con.prepareStatement("update person set name=?,owner=? where id=? "); //sql update query
pstmt.setString(1,name_up);
pstmt.setString(2,owner_up);
pstmt.setInt(3,hidden_id);
pstmt.executeUpdate(); //execute query
pstmt.close(); //close statement
con.close(); //close connection
return "UPDATE SUCCESS"; //if valid return "UPDATE SUCCESS" string
}
catch(Exception e)
{
e.printStackTrace();
}
return "FAIL UPDATE"; //if invalid return "FAIL UPDATE" string
}
}
index.jsp
Within this page, we have extracted all records that are stored by users from the person table. See records that are arranged in table format.
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Owner</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<%
String url="jdbc:mysql://localhost:3306/db_mvcoperation"; //database connection url string
String username="root"; //database connection username
String password=""; //database password
try
{
Class.forName("com.mysql.jdbc.Driver"); //load driver
Connection con=DriverManager.getConnection(url,username,password); //create connection
PreparedStatement pstmt=null; //create statement
pstmt=con.prepareStatement("select * from person"); //sql select query
ResultSet rs=pstmt.executeQuery(); //execute query and set in ResultSet object rs.
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt("id")%></td>
<td><%=rs.getString("name")%></td>
<td><%=rs.getString("owner")%></td>
<td><a href="edit.jsp?edit_id=<%=rs.getInt("id")%>">Edit</a></td>
<td><a href="delete.jsp?delete_id=<%=rs.getInt("id")%>">Delete</a></td>
</tr>
<%
}
pstmt.close(); //close statement
con.close(); //close connection
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</table>
delete.jsp
Create a new page to delete specific records like "delete.jsp" just hyperlink the name of this page along with the record Id.
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%
if(request.getParameter("delete_id")!=null) //get delete_id from index.jsp page with href link and check not null after continue
{
int id=Integer.parseInt(request.getParameter("delete_id")); //get delete_id store in "id" variable
String url="jdbc:mysql://localhost:3306/db_mvcoperation"; //database connection url string
String username="root"; //database connection username
String password=""; //database password
try
{
Class.forName("com.mysql.jdbc.Driver"); //load driver
Connection con=DriverManager.getConnection(url,username,password); //create connection
PreparedStatement pstmt=null; //create statement
pstmt=con.prepareStatement("delete from person where id=? "); //sql delete query
pstmt.setInt(1,id);
pstmt.executeUpdate(); //execute query
RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); //after delete success forward index.jsp page
rd.forward(request, response);
pstmt.close(); //close statement
con.close(); //close connection
}
catch(Exception e)
{
e.printStackTrace();
}
}
%>
web.xml
See the Configuration of web.xml file below. The whole tag helps map the available AddController and EditController Servlet file in different packages.
<?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>AddController</servlet-name>
<servlet-class>com.mvc.controller.AddController</servlet-class>
</servlet>
<servlet>
<servlet-name>EditController</servlet-name>
<servlet-class>com.mvc.controller.EditController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddController</servlet-name>
<url-pattern>/AddController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditController</servlet-name>
<url-pattern>/EditController</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Read Also:
Java MVC Login and Register Script Using JSP & Servlet With MySQL
How to Send Email After Registration with Activation Link in Java
Restful Webservice Example in Java
Download Codes
Super very helpfull
ReplyDeleteThanks. Cheers
ReplyDelete