Employee Information Retrieval with MVC and Servlet

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to implement an employee information retrieval feature using the MVC architecture and Servlet2.x. You will create a search box on the index page where users can enter the employee ID to search, and then display the employee information on a separate page.

👀 Preview

Preview

🎯 Tasks

In this project, you will learn:

  • How to create a search box on the index page to allow users to enter the employee ID
  • How to implement the entity class to represent the employee data
  • How to implement the JDBC utility class to get a database connection
  • How to implement the DAO class to retrieve employee information from the database
  • How to implement the controller class to handle the requests and forward the employee data to the JSP page
  • How to implement the JSP page to display the queried employee information

🏆 Achievements

After completing this project, you will be able to:

  • Use the MVC architecture to structure your web application
  • Use Servlet2.x to handle HTTP requests and responses
  • Interact with a database using JDBC
  • Use JSP to display dynamic data on a web page

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java/ProgrammingTechniquesGroup -.-> java/method_overriding("`Method Overriding`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/FileandIOManagementGroup -.-> java/io("`IO`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/jdbc("`JDBC`") subgraph Lab Skills java/method_overriding -.-> lab-300392{{"`Employee Information Retrieval with MVC and Servlet`"}} java/annotation -.-> lab-300392{{"`Employee Information Retrieval with MVC and Servlet`"}} java/oop -.-> lab-300392{{"`Employee Information Retrieval with MVC and Servlet`"}} java/io -.-> lab-300392{{"`Employee Information Retrieval with MVC and Servlet`"}} java/jdbc -.-> lab-300392{{"`Employee Information Retrieval with MVC and Servlet`"}} end

In this step, you will create a search box on the index page where users can enter the employee ID to search.

  1. Open the index.jsp file located in the EmployeeInfo/src/main/webapp directory.

  2. Add the following HTML code to create the search box:

<form action="/findEmpByEid" method="get">
  <input type="text" name="employeeId" /><input type="submit" value="search" />
</form>

This form will send a GET request to the /findEmpByEid URL with the employeeId parameter when the user clicks the "search" button.

Implement the Employee Entity Class

In this step, you will implement the Employee.java entity class based on the fields in the employees table.

  1. Open the Employee.java file located in the EmployeeInfo/src/main/java/org/labex/entity directory.

  2. Add the following code to define the fields and their corresponding getters and setters:

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

    // Getters and setters
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // Implement the rest of the getters and setters
}

Implement the JDBC Utility Class

In this step, you will implement the JdbcUtil.java class to provide a method to get a database connection.

  1. Open the JdbcUtil.java file located in the EmployeeInfo/src/main/java/org/labex/jdbc directory.

  2. Add the following code to implement the getConn() method:

public class JdbcUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

This method will return a database connection using the provided URL, username, and password.

Implement the DAO Class

In this step, you will implement the EmployeeDao.java class to provide a method to retrieve employee information.

  1. Open the EmployeeDao.java file located in the EmployeeInfo/src/main/java/org/labex/dao directory.

  2. Add the following code to implement the getEmployee() method:

public class EmployeeDao {
    public Employee getEmployee(Integer employeeId) {
        Connection conn = JdbcUtil.getConn();
        String sql = "select * from employees where employee_id = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        Employee employee = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setInt(1, employeeId);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                employee = new Employee();
                employee.setId(resultSet.getInt(1));
                employee.setName(resultSet.getString(2));
                employee.setGender(resultSet.getInt(3));
                employee.setPhone(resultSet.getString(4));
                employee.setEmail(resultSet.getString(5));
                employee.setAddress(resultSet.getString(6));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return employee;
    }
}

This method uses the getConn() method from JdbcUtil.java to get a database connection, and then uses the employee ID passed from the controller to query the database and return an Employee object.

Implement the Controller Class

In this step, you will implement the EmployeeController.java class to handle the requests to retrieve employee information.

  1. Open the EmployeeController.java file located in the EmployeeInfo/src/main/java/org/labex/controller directory.

  2. Add the following code to implement the doGet() and doPost() methods:

@WebServlet("/findEmpByEid")
public class EmployeeController extends HttpServlet {
    EmployeeDao employeeDao = new EmployeeDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String employeeId = req.getParameter("employeeId");
        Employee employee = employeeDao.getEmployee(Integer.parseInt(employeeId));
        req.setAttribute("employee", employee);
        req.getRequestDispatcher("info.jsp").forward(req, resp);
    }
}

The doGet() method retrieves the employeeId parameter from the request, uses the EmployeeDao class to get the employee information, stores it in the request, and then forwards the request to the info.jsp page to display the employee information.

Implement the JSP Page

In this step, you will implement the info.jsp file to display the queried employee information.

  1. Open the info.jsp file located in the EmployeeInfo/src/main/webapp directory.

  2. Add the following code to create a table to display the employee information:

<%@ page import="org.labex.entity.Employee" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Employee Information</title>
    <style>
        th, td {
            border: 1px solid black;
            padding: 8px;
        }
    </style>
</head>
<body>
    <% Object employeeObj = request.getAttribute("employee");
    if (employeeObj != null) {
        Employee employee = (Employee) employeeObj; %>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Phone Number</th>
                <th>Email</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><%= employee.getId() %></td>
                <td><%= employee.getName() %></td>
                <td><%= employee.getGender() == 1 ? "man" : "woman" %></td>
                <td><%= employee.getPhone() %></td>
                <td><%= employee.getEmail() %></td>
                <td><%= employee.getAddress() %></td>
            </tr>
        </tbody>
    </table>
    <% } else { %>
    <p>Information not found.</p>
    <% } %>
</body>
</html>

This JSP page retrieves the employee object from the request, and then displays the employee information in a table.

  1. Switch to the EmployeeInfo directory and use the following command to start the service.
cd ~/project/EmployeeInfo/
mvn clean tomcat7:run

The expected result of the queried employee information is as follows:

result

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like