Professional Documents
Culture Documents
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.
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
<!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;
empDBHandler.java
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;
}
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);
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("<tr><th>Id</th><th>Name</th><th>Dept</th><th>Update</th><th>Delete<
/th></tr>");
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;
/**
* @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);
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.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);
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.
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;
}
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;
}
Output
After clicking on the “View Employees” link you will get the below screens: