You are on page 1of 21

Example: CRUD in Servlet

In this example, we will create a simple CRUD (Create Read Update Delete) User
Management Web Application using HTML, Servlet, and MySQL. First, let’s create the
database and employee table using the following SQL scripts.

create database database;

use database;

Create the “emp” table in MySQL Database with auto-incrementing “id” using sequence.
There are 3 fields in it: id, name, and dept.
Index.html

Index.html is a form used to insert data into the database

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1" />
<title>CRUD Servlet</title>
</head>
<body>
<h1>Enter details to save in database</h1>
<form action="reportservlet" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Dept:</td>
<td><input type="text" name="dept" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" /></td>
</tr>
</table>
</form>
<br />
<a href="viewservlet">view employees</a>
</body>
</html>

Emp.java

Emp.java contains the POJO (Plain Old Java Object). Each class in this package
represents the database table.

package com.servlet;
public class Emp
{
private int id;
private String name, dept;

public int getId ()


{
return id;
}

public void setId (int id)


{
this.id = id;
}

public String getName ()


{
return name;
}

public void setName (String name)


{
this.name = name;
}

public String getDept ()


{
return dept;
}

public void setDept (String dept)


{
this.dept = dept;
}
}

empDBHandler.java

EmpDBHandler.java class handles the database connection to our MySQL server. It


contains the necessary information for the connection.

package com.servlet;
import java.util.*;
import java.sql.*;
public class empDBHandler
{
public static Connection getConnection ()
{
Connection con = null;
try
{
Class.forName ("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("jdbc:mysql://localhost:3306/database","root", "876745");;
}
catch (Exception e)
{
System.out.println (e);
}
return con;
}

public static int save(Emp e)


{
int status = 0;
try
{
Connection con = empDBHandler.getConnection ();
PreparedStatement ps =con.prepareStatement ("insert into
emp(name,dept) values (?,?)");
ps.setString (1, e.getName ());
ps.setString (2, e.getDept ());
status = ps.executeUpdate ();
con.close ();
}
catch (Exception ex)
{
ex.printStackTrace ();
}
return status;
}

public static int update (Emp e)


{
int status = 0;
try
{
Connection con = empDBHandler.getConnection ();
PreparedStatement ps = con.prepareStatement ("update emp set
name=?,dept=? where id=?");
ps.setString (1, e.getName ());
ps.setString (2, e.getDept ());
ps.setInt (3, e.getId ());
status = ps.executeUpdate ();
con.close ();
}
catch (Exception ex)
{
ex.printStackTrace ();
}
return status;
}

public static int delete (int id)


{
int status = 0;
try
{
Connection con = empDBHandler.getConnection ();
PreparedStatement ps =con.prepareStatement ("delete from emp where
id=?");
ps.setInt (1, id);
status = ps.executeUpdate ();
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
return status;
}

public static Emp getEmployeeById (int id)


{
Emp e = new Emp ();
try
{
Connection con = empDBHandler.getConnection ();
PreparedStatement ps =con.prepareStatement ("select * from emp
where id=?");
ps.setInt (1, id);
ResultSet rs = ps.executeQuery ();
if (rs.next ())
{
e.setId (rs.getInt (1));
e.setName (rs.getString (2));
e.setDept (rs.getString (3));
}
con.close ();
}
catch (Exception ex)
{
ex.printStackTrace ();
}
return e;
}

public static List < Emp > getAllEmployees ()


{
List<Emp> list = new ArrayList<Emp>();
try
{
Connection con = empDBHandler.getConnection ();
PreparedStatement ps = con.prepareStatement ("select * from emp");
ResultSet rs = ps.executeQuery ();
while (rs.next ())
{
Emp e = new Emp ();
e.setId (rs.getInt (1));
e.setName (rs.getString (2));
e.setDept (rs.getString (3));

list.add (e);
}
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
return list;
}
}

reportservlet.java

After entering details into the form page, reportservlet.java helps you to save all the records
into the MySQL database and give the following message: “Record Saved Successfully”.

package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet ("/reportservlet")
public class reportservlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter ();
String name = request.getParameter ("name");
String dept = request.getParameter ("dept");
Emp e = new Emp ();
e.setName (name);
e.setDept (dept);

int status = empDBHandler.save (e);


if (status > 0)
{
out.print ("<p>Record saved successfully!</p>");
request.getRequestDispatcher ("Index.html").include (request,
response);
}
else
{
out.println ("Sorry! unable to save record");
}
out.close ();
}
}

viewservlet.java

After adding records into the database successfully, viewservlet.java helps you to see all
the data from the database into the webpage directly.

package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/viewservlet")
public class viewservlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter ();
out.println ("<a href='Index.html'>Add Employee</a>");
out.println ("<h1>Employees List</h1>");
List <Emp> list = empDBHandler.getAllEmployees();

out.print ("<table border='1' width='100%' ");

out.print("<tr><th>Id</th><th>Name</th><th>Dept</th><th>Update</th><th>Delete<
/th></tr>");

for (Emp e:list)


{
out.print ("<tr><td>" + e.getId () + "</td><td>" + e.getName () +
"</td><td>" + e.getDept () +
"</td><td><a href='updateservlet?id=" + e.getId () +
"'>update</a></td> <td><a href='deleteservlet?id=" +
e.getId () + "'>delete</a></td></tr>");
}
out.print ("</table>");
out.close ();
}
}

addservlet.java

addservlet.java helps you to add more data into the database by clicking the “Add
Employee” link.

package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class addservlet
*/
@WebServlet("/addservlet")
public class addservlet extends HttpServlet
{
private static final long serialVersionUID = 1L;

protected void processRequest (HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException
{
response.setContentType ("text/html;charset=UTF-8");
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
@Override
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
processRequest (request, response);
try
{
PrintWriter out = response.getWriter ();
String eid = request.getParameter ("id");
int id = Integer.parseInt (eid);
String ename = request.getParameter ("name");
String dept = request.getParameter ("dept");
try
{
Class.forName ("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/database", "root", "876745");
Statement stmt = con.createStatement ();
stmt.executeUpdate ("insert into emp values (" + id + ",'" +
ename + "', '" + dept + "')");
out.println ("<h1>Record Inserted Successfully</h1>");
String sql = "select * from emp";
ResultSet rs = stmt.executeQuery (sql);
out.println ("<form action = 'viewservlet' method='post'>");
out.print ("<tr><a href ='viewservlet'>View
Employee</a></td></tr>");
out.println ("</tr>");
out.println ("</table>");
out.println ("</form>");
rs.close ();
stmt.close ();
con.close ();

}
catch (SQLException se)
{
throw new RuntimeException ("Cannot Connect the Database!", se);
}

}
catch (ClassNotFoundException cnfe)
{
}
}
}

deleteservlet.java

deleteservlet.java helps you to delete the data from the database by the “id”.

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

@WebServlet("/deleteservlet")
public class deleteservlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter ();
String sid = request.getParameter ("id");
int id = Integer.parseInt (sid);
empDBHandler.delete (id);

int status = empDBHandler.delete (id);


if (status > 0)
{
out.print ("<p>Record deleted successfully!</p>");
response.sendRedirect ("viewservlet");
}
else
{
out.println ("Sorry! unable to delete record");
}
response.sendRedirect ("viewservlet");
}
}

updateservlet.java

If you want to update any data into the database, click on the “update” link, then the control
will go to updateservlet.java where you can update your details and click on the “update”
button.

package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/updateservlet")
public class updateservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<h1>Update Employee</h1>");
String sid=request.getParameter("id");
int id=Integer.parseInt(sid);
Emp e=empDBHandler.getEmployeeById(id);

out.print("<form action='updateservlet2' method='post'>");


out.print("<table>");
out.print("<tr><td></td><td><input type='hidden' name='id'
value='"+e.getId()+"'/></td></tr>");
out.print("<tr><td>Name:</td><td><input type='text' name='name'
value='"+e.getName()+"'/></td></tr>");
out.print("<tr><td>Dept:</td><td><input type='text' name='dept'
value='"+e.getDept()+"'/> </td></tr>");

out.print("<tr><td colspan='2'><input type='submit' value='Update


'/></td></tr>");
out.print("</table>");
out.print("</form>");

out.close();
}
}

updateservlet2.java

After clicking on the “update” button, the control will go to updateservlet2.java which helps
you to update the mentioned details into the database by id.

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

@WebServlet("/updateservlet2")
public class updateservlet2 extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter ();
String sid = request.getParameter ("id");
int id = Integer.parseInt (sid);
String name = request.getParameter ("name");
String dept = request.getParameter ("dept");
Emp e = new Emp ();
e.setId (id);
e.setName (name);
e.setDept (dept);

int status = empDBHandler.update (e);


if (status > 0)
{
out.println ("Record updated succesfully...");
response.sendRedirect ("viewservlet");
}
else
{
out.println ("Sorry! unable to update record");
}
out.close ();
}
}

Output

Run your project and you will get the following form on your page. Enter your details and
click the “Save” button. After clicking on the “Save” button, your details will be saved into the
database.
Once the record has been saved successfully into your database, you will get the following
screen. Click on the “view employees” link to view the list of data you saved.
After clicking on the “view employees” link you will get the following output. If you want to
add more employees to the database click on the “add employees” link where you will be
redirected to the Index.html page where you can add your details.

If you want to update any data click on the “update” link which will redirect you to
“updateservlet.java”. And to delete particular data click on the “delete” link which will redirect
the control to deleteservlet.java and helps you delete the particular data from the database.

After clicking on the “update” link you will get the following webpage where you can update
your details and press the “Update” button, which will move your control to
“updateservlet2.java” and it helps you to update the details in your database.

After clicking on the “Update” button you will be available with the following page where you
can able to view the updated data from your database.
Pagination in Servlet

Pagination is the process of dividing a large number of records into multiple parts. The user
has a navigation interface to access each page with a specific page link. It may take time to
load all records on a single page, so it is always recommended to create pagination. It is
mostly used when there is lots of data in the database or there are many comments to be
shown on one page.

Example

In this servlet pagination example, we are using the MySQL database to fetch records.
Here, we have created the “emp” table in the “database” database. The emp table has 3
fields: id, name, and dept.

index.html

First, we need the index.html file which will be our welcome page.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<a href="ViewServlet?page=1">View Employees</a>
</body>
</html>

Emp.java

This is our model class means Java bean class, we have used the same as the previous
example.

public class Emp


{
private int id;
private String name;
private String dept;

public int getId ()


{
return id;
}

public void setId (int id)


{
this.id = id;
}

public String getName ()


{
return name;
}

public void setName (String name)


{
this.name = name;
}

public String getDept ()


{
return dept;
}

public void setDept (String dept)


{
this.dept = dept;
}
}

EmpDao.java

import java.util.*;
import java.sql.*;
public class EmpDao
{
public static Connection getConnection ()
{
Connection con = null;
try
{
Class.forName ("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/database", "root", "876745");;
}
catch (Exception e)
{
System.out.println (e);
}
return con;
}

public static List<Emp> getRecords (int start, int total)


{
List<Emp> list = new ArrayList<Emp>();
try
{
Connection con = getConnection ();
PreparedStatement ps = con.prepareStatement ("select * from emp
limit " + (start - 1) + "," + total);
ResultSet rs = ps.executeQuery ();
while (rs.next ())
{
Emp e = new Emp ();
e.setId (rs.getInt (1));
e.setName (rs.getString (2));
e.setDept (rs.getString (3));
list.add (e);
}
con.close ();
}
catch (Exception e)
{
System.out.println (e);
}
return list;
}
}

ViewServlet.java

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

@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter ();
String spageid = request.getParameter ("page");
int pageid = Integer.parseInt (spageid);
int total = 5;
if (pageid == 1)
{
}
else
{
pageid = pageid - 1;
pageid = pageid * total + 1;
}

List<Emp> list = EmpDao.getRecords(pageid, total);


out.println ("<h1>Employees List Page No : " + spageid + "</h1>");

out.print ("<table border='1'");


out.print ("<tr><th>Id</th><th>Name</th><th>Dept</th></tr>");
for(Emp e:list)
{
out.print ("<tr><td>" + e.getId () + "</td><td>" + e.getName ()
+"</td><td>" + e.getDept () + "</td></tr>");
}
out.print ("</table>");
out.print ("<a href='ViewServlet?page=1'>1</a>");
out.print ("<a href='ViewServlet?page=2'>2</a>");
out.print ("<a href='ViewServlet?page=3'>3</a>");
out.close ();
}
}

Output

Run your code to get the following output

After clicking on the “View Employees” link you will get the below screens:

You might also like