📜  Servlet – CRUD(1)

📅  最后修改于: 2023-12-03 15:05:10.886000             🧑  作者: Mango

Servlet – CRUD

Servlets are a Java technology used to create web applications. CRUD is an acronym for Create, Read, Update, and Delete, which are the basic operations used in all database systems.

Servlets can be used to perform CRUD operations on databases. In this tutorial, we will create a simple web application that allows users to perform CRUD operations on a MySQL database.

Technologies used:
  • Java 1.8+
  • MySQL database
  • Eclipse IDE
  • Apache Tomcat 9.0 server
Application architecture

The application will consist of two main layers:

Database layer

This layer will contain the MySQL database where the data will be stored. We will use the MySQL JDBC driver to connect to the database and perform CRUD operations.

Servlet layer

This layer will be responsible for handling HTTP requests from the web client and calling the appropriate methods in the database layer to perform CRUD operations.

Implementation
Step 1: Create the MySQL database

First, we need to create a MySQL database to store our data. We will create a table called "employees" with the following fields:

CREATE DATABASE IF NOT EXISTS employees;
USE employees;

CREATE TABLE IF NOT EXISTS employees (
  id INT(11) NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL,
  address VARCHAR(100) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 2: Create the Java project in Eclipse

Next, we will create a Java project in Eclipse and add the necessary dependencies to our project. We will add the following dependencies to our pom.xml file:

<dependencies>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
  </dependency>

  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
  </dependency>
</dependencies>
Step 3: Create the Employee model class

We will create a Java class called "Employee" to represent an employee entity. The class will contain the following fields:

public class Employee {
  private int id;
  private String name;
  private String email;
  private String address;
  private String phone;

  // constructors, getters and setters
}
Step 4: Create the DAO class

We will create a Java class called "EmployeeDAO" to handle database operations. The class will contain methods to perform CRUD operations on the "employees" table.

public class EmployeeDAO {
  // JDBC connection variables
  private String jdbcURL;
  private String jdbcUsername;
  private String jdbcPassword;
  private Connection jdbcConnection;

  // constructor
  public EmployeeDAO(String jdbcURL, String jdbcUsername, String jdbcPassword) {
    this.jdbcURL = jdbcURL;
    this.jdbcUsername = jdbcUsername;
    this.jdbcPassword = jdbcPassword;
  }

  // CRUD methods
  public void createEmployee(Employee employee) {
    // implementation
  }

  public Employee getEmployeeById(int id) {
    // implementation
  }

  public List<Employee> getAllEmployees() {
    // implementation
  }

  public void updateEmployee(Employee employee) {
    // implementation
  }

  public void deleteEmployee(int id) {
    // implementation
  }
}
Step 5: Implement the CRUD methods

We will now implement the CRUD methods in the EmployeeDAO class.

createEmployee(Employee employee)

This method will insert a new employee record into the database.

public void createEmployee(Employee employee) {
  String sql = "INSERT INTO employees (name, email, address, phone) VALUES (?, ?, ?, ?)";
  try {
    getConnection();
    PreparedStatement statement = jdbcConnection.prepareStatement(sql);
    statement.setString(1, employee.getName());
    statement.setString(2, employee.getEmail());
    statement.setString(3, employee.getAddress());
    statement.setString(4, employee.getPhone());
    statement.executeUpdate();
    statement.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
}

getEmployeeById(int id)

This method will retrieve an employee record from the database based on the given ID.

public Employee getEmployeeById(int id) {
  String sql = "SELECT * FROM employees WHERE id = ?";
  Employee employee = null;
  try {
    getConnection();
    PreparedStatement statement = jdbcConnection.prepareStatement(sql);
    statement.setInt(1, id);
    ResultSet resultSet = statement.executeQuery();
    if (resultSet.next()) {
      employee = new Employee();
      employee.setId(resultSet.getInt("id"));
      employee.setName(resultSet.getString("name"));
      employee.setEmail(resultSet.getString("email"));
      employee.setAddress(resultSet.getString("address"));
      employee.setPhone(resultSet.getString("phone"));
    }
    resultSet.close();
    statement.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
  return employee;
}

getAllEmployees()

This method will retrieve all employee records from the database.

public List<Employee> getAllEmployees() {
  String sql = "SELECT * FROM employees";
  List<Employee> employees = new ArrayList<>();
  try {
    getConnection();
    Statement statement = jdbcConnection.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);
    while (resultSet.next()) {
      Employee employee = new Employee();
      employee.setId(resultSet.getInt("id"));
      employee.setName(resultSet.getString("name"));
      employee.setEmail(resultSet.getString("email"));
      employee.setAddress(resultSet.getString("address"));
      employee.setPhone(resultSet.getString("phone"));
      employees.add(employee);
    }
    resultSet.close();
    statement.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
  return employees;
}

updateEmployee(Employee employee)

This method will update an existing employee record in the database.

public void updateEmployee(Employee employee) {
  String sql = "UPDATE employees SET name = ?, email = ?, address = ?, phone = ? WHERE id = ?";
  try {
    getConnection();
    PreparedStatement statement = jdbcConnection.prepareStatement(sql);
    statement.setString(1, employee.getName());
    statement.setString(2, employee.getEmail());
    statement.setString(3, employee.getAddress());
    statement.setString(4, employee.getPhone());
    statement.setInt(5, employee.getId());
    statement.executeUpdate();
    statement.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
}

deleteEmployee(int id)

This method will delete an employee record from the database based on the given ID.

public void deleteEmployee(int id) {
  String sql = "DELETE FROM employees WHERE id = ?";
  try {
    getConnection();
    PreparedStatement statement = jdbcConnection.prepareStatement(sql);
    statement.setInt(1, id);
    statement.executeUpdate();
    statement.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
}
Step 6: Create the Servlet classes

We will create Java servlet classes to handle HTTP requests from the web client and call the appropriate methods in the DAO class to perform CRUD operations.

CreateEmployeeServlet

This servlet will handle the HTTP POST request to create a new employee record.

public class CreateEmployeeServlet extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    String email = req.getParameter("email");
    String address = req.getParameter("address");
    String phone = req.getParameter("phone");

    Employee employee = new Employee();
    employee.setName(name);
    employee.setEmail(email);
    employee.setAddress(address);
    employee.setPhone(phone);

    EmployeeDAO dao = new EmployeeDAO("jdbc:mysql://localhost:3306/employees", "root", "password");
    dao.createEmployee(employee);

    resp.sendRedirect(req.getContextPath() + "/employees.jsp");
  }
}

GetAllEmployeesServlet

This servlet will handle the HTTP GET request to retrieve all employee records.

public class GetAllEmployeesServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    EmployeeDAO dao = new EmployeeDAO("jdbc:mysql://localhost:3306/employees", "root", "password");
    List<Employee> employees = dao.getAllEmployees();
    req.setAttribute("employees", employees);
    
    RequestDispatcher dispatcher = req.getRequestDispatcher("/employees.jsp");
    dispatcher.forward(req, resp);
  }
}

UpdateEmployeeServlet

This servlet will handle the HTTP POST request to update an existing employee record.

public class UpdateEmployeeServlet extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int id = Integer.parseInt(req.getParameter("id"));
    String name = req.getParameter("name");
    String email = req.getParameter("email");
    String address = req.getParameter("address");
    String phone = req.getParameter("phone");

    Employee employee = new Employee();
    employee.setId(id);
    employee.setName(name);
    employee.setEmail(email);
    employee.setAddress(address);
    employee.setPhone(phone);

    EmployeeDAO dao = new EmployeeDAO("jdbc:mysql://localhost:3306/employees", "root", "password");
    dao.updateEmployee(employee);

    resp.sendRedirect(req.getContextPath() + "/employees.jsp");
  }
}

DeleteEmployeeServlet

This servlet will handle the HTTP POST request to delete an employee record.

public class DeleteEmployeeServlet extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int id = Integer.parseInt(req.getParameter("id"));

    EmployeeDAO dao = new EmployeeDAO("jdbc:mysql://localhost:3306/employees", "root", "password");
    dao.deleteEmployee(id);

    resp.sendRedirect(req.getContextPath() + "/employees.jsp");
  }
}
Step 7: Create the web pages

Finally, we will create the web pages to display the employee records and allow users to create, update, and delete records.

index.jsp

This page will be the landing page of the application.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Employee Management System</title>
</head>
<body>
  <a href="employees.jsp">View employees</a>
</body>
</html>

employees.jsp

This page will display a list of all employee records and allow users to create, update, and delete records.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Employees</title>
</head>
<body>
  <h1>Employees</h1>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Address</th>
        <th>Phone</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <c:forEach var="employee" items="${employees}">
        <tr>
          <td>${employee.id}</td>
          <td>${employee.name}</td>
          <td>${employee.email}</td>
          <td>${employee.address}</td>
          <td>${employee.phone}</td>
          <td>
            <form method="post" action="update-employee.jsp">
              <input type="hidden" name="id" value="${employee.id}">
              <input type="submit" value="Update">
            </form>
            <form method="post" action="delete-employee">
              <input type="hidden" name="id" value="${employee.id}">
              <input type="submit" value="Delete">
            </form>
          </td>
        </tr>
      </c:forEach>
    </tbody>
  </table>
  <h2>Create employee</h2>
  <form method="post" action="create-employee">
    <label>Name</label>
    <input type="text" name="name"><br>
    <label>Email</label>
    <input type="email" name="email"><br>
    <label>Address</label>
    <input type="text" name="address"><br>
    <label>Phone</label>
    <input type="tel" name="phone"><br>
    <input type="submit" value="Create">
  </form>
</body>
</html>

create-employee.jsp

This page will allow users to create a new employee record.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Create Employee</title>
</head>
<body>
  <h1>Create Employee</h1>
  <form method="post" action="create-employee">
    <label>Name</label>
    <input type="text" name="name"><br>
    <label>Email</label>
    <input type="email" name="email"><br>
    <label>Address</label>
    <input type="text" name="address"><br>
    <label>Phone</label>
    <input type="tel" name="phone"><br>
    <input type="submit" value="Create">
  </form>
</body>
</html>

update-employee.jsp

This page will allow users to update an existing employee record.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Update Employee</title>
</head>
<body>
  <h1>Update Employee</h1>
  <form method="post" action="update-employee">
    <input type="hidden" name="id" value="${param.id}">
    <label>Name</label>
    <input type="text" name="name" value="${employee.name}"><br>
    <label>Email</label>
    <input type="email" name="email" value="${employee.email}"><br>
    <label>Address</label>
    <input type="text" name="address" value="${employee.address}"><br>
    <label>Phone</label>
    <input type="tel" name="phone" value="${employee.phone}"><br>
    <input type="submit" value="Update">
  </form>
</body>
</html>
Conclusion

In this tutorial, we learned how to use Servlets to perform CRUD operations on a MySQL database. We created a Java project in Eclipse, added the necessary dependencies, implemented the CRUD methods, created the Servlet classes, and created the web pages to display the data. This is just a basic example, but the same techniques can be applied to create more complex web applications.