TechieClues TechieClues
Updated date Apr 03, 2023
In this article, we will discuss how to perform CRUD operations in Java servlets with sample code, explanations, and more.

Introduction:

CRUD operations are basic operations that are performed on databases. These operations stand for Create, Read, Update, and Delete. Java Servlets are Java-based web components that are used to create dynamic web pages. Java Servlets can be used to perform CRUD operations on databases by integrating them with SQL databases. In this article, we will be discussing how to perform CRUD operations in Java servlets with sample code, and explanations.

Prerequisites:

Before starting with the CRUD operations in Java servlets, we need to have some prerequisites that include the following:

  1. Java Development Kit (JDK): We need to install JDK on our system in order to write and run Java servlets.

  2. Eclipse IDE: Eclipse is an Integrated Development Environment (IDE) that is used to develop Java applications. We will be using Eclipse IDE to develop Java servlets.

  3. Tomcat Server: Tomcat is a Java Servlet container that is used to deploy and run Java servlets.

  4. MySQL Database: MySQL is a popular open-source Relational Database Management System (RDBMS) that is used to store and manage data.

Creating a MySQL Database:

Before we start implementing the CRUD operations, we need to create a MySQL database. For this purpose, we will use the following SQL script:

CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL,
password varchar(50) NOT NULL,
PRIMARY KEY (id)
);

The above script creates a database named 'mydb' and a table named 'users' with four columns, namely 'id', 'name', 'email', and 'password'. The 'id' column is the primary key of the table.

Configuring the Project:

Once we have created the database, we need to configure our project in Eclipse. For this purpose, we need to follow the following steps:

  1. Open Eclipse IDE and create a new Dynamic Web Project.

  2. Set the project name as 'CRUDOperations'.

  3. Set the Target Runtime as 'Apache Tomcat v10.0'.

  4. Click on Finish.

  5. Right-click on the project and select Properties.

  6. In the Properties window, select Java Build Path.

  7. Click on Add External JARs and select the MySQL connector JAR file.

  8. Click on Apply and Close.

Now, our project is configured and ready to use.

Implementing the CRUD Operations:

Create Operation:

To implement the Create operation, we need to create a servlet that will handle the HTTP POST requests and insert the data into the MySQL database. The following code shows how to implement the Create operation:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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("/CreateServlet")
public class CreateServlet extends HttpServlet {
  private static final long serialVersionUID = 1 L;
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String password = request.getParameter("password");

    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");

      PreparedStatement ps = con.prepareStatement("insert into users(name,email,password) values(?,?,?)");

      ps.setString(1, name);
      ps.setString(2, email);
      ps.setString(3, password);
      int i = ps.executeUpdate();
      if (i > 0) {
        out.println("<script type=\"text/javascript\">");
        out.println("alert('User created successfully');");
        out.println("location='index.jsp';");
        out.println("</script>");
      } else {
        out.println("<script type=\"text/javascript\">");
        out.println("alert('User creation failed');");
        out.println("location='create.jsp';");
        out.println("</script>");
      }
    } catch (Exception e) {
      out.println("<script type=\"text/javascript\">");
      out.println("alert('An error occurred: " + e.getMessage() + "');");
      out.println("location='create.jsp';");
      out.println("</script>");
    }

    out.close();
  }
}

Explanation:

1. We import the necessary classes and interfaces that are required for implementing the Create operation.

2. We create a class named CreateServlet that extends the HttpServlet class.

3. We override the doPost() method that handles the HTTP POST requests.

4. We set the content type of the response to "text/html" and create a PrintWriter object that will be used to send the response to the client.

5. We retrieve the values of the name, email, and password parameters from the request.

6. We load the MySQL driver using the Class.forName() method.

7. We create a connection to the MySQL database using the DriverManager.getConnection() method.

8. We create a PreparedStatement object that inserts the data into the 'users' table.

9. We set the values of the parameters in the PreparedStatement object.

10. We execute the PreparedStatement using the executeUpdate() method.

11. If the PreparedStatement is executed successfully, we display a success message using the JavaScript alert() function and redirect the user to the index.jsp page.

12. If the PreparedStatement execution fails, we display an error message using the JavaScript alert() function and redirect the user to the create.jsp page.

13. If any exception occurs, we catch it and display an error message using the JavaScript alert() function and redirect the user to the create.jsp page.

Read Operation:

To implement the Read operation, we must create a servlet that will handle the HTTP GET requests and fetch the data from the MySQL database. The following code shows how to implement the Read operation:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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;

@WebServlet("/ReadServlet")
public class ReadServlet extends HttpServlet {
  private static final long serialVersionUID = 1 L;
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");

      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from users");

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Users List</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Users List</h1>");
      out.println("<table>");
      out.println("<tr>");
      out.println("<th>ID</th>");
      out.println("<th>Name</th>");
      out.println("<th>Email</th>");
      out.println("<th>Password</th>");
      out.println("</tr>");

      while (rs.next()) {
        out.println("<tr>");
        out.println("<td>"
          rs.getInt("id") + "</td>");
        out.println("<td>" + rs.getString("name") + "</td>");
        out.println("<td>" + rs.getString("email") + "</td>");
        out.println("<td>" + rs.getString("password") + "</td>");
        out.println("</tr>");
      }
      out.println("</table>");
      out.println("</body>");
      out.println("</html>");

      con.close();
    } catch (Exception e) {
      out.println("<script type=\"text/javascript\">");
      out.println("alert('An error occurred: " + e.getMessage() + "');");
      out.println("location='index.jsp';");
      out.println("</script>");
    }

    out.close();
  }

}

Explanation:

1. We import the necessary classes and interfaces that are required for implementing the Read operation.

2. We create a class named ReadServlet that extends the HttpServlet class.

3. We override the doGet() method that handles the HTTP GET requests.

4. We set the content type of the response to "text/html" and create a PrintWriter object that will be used to send the response to the client.

5. We load the MySQL driver using the Class.forName() method.

6. We create a connection to the MySQL database using the DriverManager.getConnection() method.

7. We create a Statement object that executes the SQL query to fetch the data from the 'users' table.

8. We execute the Statement using the executeQuery() method.

9. We iterate over the ResultSet and print the data in an HTML table.

10. If any exception occurs, we catch it and display an error message using the JavaScript alert() function and redirect the user to the index.jsp page.

Update Operation:

To implement the Update operation, we need to create a servlet that will handle the HTTP POST requests and update the data in the MySQL database. The following code shows how to implement the Update operation:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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 = 1 L;
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
      int id = Integer.parseInt(request.getParameter("id"));
      String name = request.getParameter("name");
      String email = request.getParameter("email");
      String password = request.getParameter("password");

      Class.forName("com.mysql.cj.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");

      PreparedStatement ps = con.prepareStatement("update users set name=?, email=?, password=? where id=?");
      ps.setString(1, name);
      ps.setString(2, email);
      ps.setString(3, password);
      ps.setInt(4, id);

      int i = ps.executeUpdate();
      if (i > 0) {
        out.println("<script type=\"text/javascript\">");
        out.println("alert('User updated successfully');");
        out.println("location='index.jsp';");
        out.println("</script>");
      } else {
        out.println("<script type=\"text/javascript\">");
        out.println("alert('User update failed');");
        out.println("location='edit.jsp?id=" + id + "';");
        out.println("</script>");
      }

      con.close();
    } catch (Exception e) {
      out.println("<script type=\"text/javascript\">");
      out.println("alert('An error occurred: " +
        e.getMessage() + "');");
      out.println("location='edit.jsp?id=" + request.getParameter("id") + "';");
      out.println("</script>");
    }
    out.close();
  }
}

Explanation:

1. We import the necessary classes and interfaces that are required for implementing the Update operation.

2. We create a class named UpdateServlet that extends the HttpServlet class.

3. We override the doPost() method that handles the HTTP POST requests.

4. We set the content type of the response to "text/html" and create a PrintWriter object that will be used to send the response to the client.

5. We get the parameters from the request object and store them in local variables.

6. We load the MySQL driver using the Class.forName() method.

7. We create a connection to the MySQL database using the DriverManager.getConnection() method.

8. We create a PreparedStatement object that executes the SQL query to update the data in the 'users' table.

9. We set the parameters in the PreparedStatement using the setString() and setInt() methods.

10. We execute the PreparedStatement using the executeUpdate() method.

11. If the update operation is successful, we display a success message using the JavaScript alert() function and redirect the user to the index.jsp page.

12. If the update operation fails, we display an error message using the JavaScript alert() function and redirect the user to the edit.jsp page with the id parameter.

Delete Operation:

To implement the Delete operation, we need to create a servlet that will handle the HTTP POST requests and delete the data from the MySQL database. The following code shows how to implement the Delete operation:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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 = 1 L;
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
      int id = Integer.parseInt(request.getParameter("id"));

      Class.forName("com.mysql.cj.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");

      PreparedStatement ps = con.prepareStatement("delete from users where id=?");
      ps.setInt(1, id);

      int i = ps.executeUpdate();
      if (i > 0) {
        out.println("<script type=\"text/javascript\">");
        out.println("alert('User deleted successfully');");
        out.println("location='index.jsp';");
        out.println("</script>");
      } else {
        out.println("<script type=\"text/javascript\">");
        out.println("alert('User deletion failed');");
        out.println("location='index.jsp';");
        out.println("</script>");
      }

      con.close();
    } catch (Exception e) {
      out.println("<script type=\"text/javascript\">");
      out.println("alert('An error occurred: " + e.getMessage() + "');");
      out.println("location='index.jsp';");
      out.println("</script>");
    }
    out.close();
  }
}

Explanation:

1. We import the necessary classes and interfaces that are required for implementing the Delete operation.

2. We create a class named DeleteServlet that extends the HttpServlet class.

3. We override the doPost() method that handles the HTTP POST requests.

4. We set the content type of the response to "text/html" and create a PrintWriter object that will be used to send the response to the client.

5. We get the id

6. We parse the id parameter from the request object and store it in a local variable.

7. We load the MySQL driver using the Class.forName() method.

8. We create a connection to the MySQL database using the DriverManager.getConnection() method.

9. We create a PreparedStatement object that executes the SQL query to delete the data from the 'users' table.

10. We set the id parameter in the PreparedStatement using the setInt() method.

11. We execute the PreparedStatement using the executeUpdate() method.

12. If the delete operation is successful, we display a success message using the JavaScript alert() function and redirect the user to the index.jsp page.

13. If the delete operation fails, we display an error message using the JavaScript alert() function and redirect the user to the index.jsp page.

Conclusion:

In this article, we have learned how to implement CRUD operations in Java Servlet. We have covered the Create, Read, Update, and Delete operations in detail with sample code and explanations. By implementing these operations, we can create a fully functional web application that can perform basic database operations. It is important to note that this is just a simple example and real-world applications may require more complex database operations. However, the basic principles remain the same, and with some modifications, these operations can be adapted to meet the specific requirements of any web application.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!