How to delete data using JSP, Servlet and MYSQL

How to delete data using JSP and servlet. In this java web application development tutorial, We will see how to add the delete button in the user list records and perform the delete operation using JSP, servlet, and MYSQL.

Steps to perform delete operation using JSP and servlet.

Step 1) Add an Delete button or link in the userList.jsp with a query string that contains the id of the selected user. And send the request to RegistrationCTL.

<a class="btn btn-danger" href="UserListCtl?id=<%=user.getId()%>">Delete</a>

Step 2)  In RegistrationCTL, Under the doGet method: get id as request and call the delete method that will take this Id as an argument and forward it to registration.jsp.

UserModel model=new UserModel();
  long id=DataUtility.getLong(request.getParameter("id"));
  if(id>0) {
    ServletUtility.setSuccessMessage("Data Deleted Successfully", request);

Delete method in

public static long delete(long id) {
  int i = 0;
  try {
    Connection conn = JDBCDataSource.getConnection();
    PreparedStatement stmt = conn.prepareStatement("DELETE from user where id=?");
    stmt.setLong(1, id);
    i = stmt.executeUpdate();

  } catch (Exception e) {
    // TODO Auto-generated catch block

  return i;

After deleting the data again get the remaining data from the database and send it to userList.jsp as request in list.


<%@page import="com.javawebapp.utility.DataUtility"%>
<%@page import="com.javawebapp.beans.UserBeans"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="com.javawebapp.utility.ServletUtility"%>
<%@ include file="header.jsp"%>
<h2>User List</h2>
<h4 style="color: red;"><%=ServletUtility.getErrorMessage(request)%></h4>
<h4 style="color: green;"><%=ServletUtility.getSuccessMessage(request)%></h4>
<table class="table table-striped">
      <th scope="col">Id</th>
      <th scope="col">Name</th>
      <th scope="col">Login</th>
      <th scope="col">MobileNo</th>
      <th scope="col">Date of Birth</th>
       <th scope="col">Action</th>
      int index=1;
      List list=ServletUtility.getList(request);
      Iterator it=list.iterator();
      UserBeans user=(UserBeans);
      <th scope="row"><%=index++%></th>
      <td><%=user.getFirstName()+" "+user.getLastName()%></td>
      <td><a class="btn btn-info" href="RegistrationCTL?id=<%=user.getId()%>">Edit</a>&nbsp;
      <a class="btn btn-danger" href="UserListCtl?id=<%=user.getId()%>">Delete</a>
<%} %>
<%@ include file="footer.jsp"%>