5.4 Creating a Servlet to Process the Request

In this section, you learn to create a Servlet to process a request.

Class Name: src/main/java/com/oracle/jdbc/samples/web/WebController.java

Github Location: WebController.java

Description: This is the main servlet that controls all the flows of the application. For every new functionality of the application, we will be adding the code to handle the new requests and responses in doPost() and processResponse() respectively.

Steps to create a Servlet:

  1. Declare the package for the WebController.java. Import Employee, EmployeeBeanImpl and Google GSON for displaying the Employee results and other dependent classes as shown below. If the particular class is not imported, then IntelliJ will display a message reminding you to import the required package.
    
    package com.oracle.jdbc.samples.web;
    import com.oracle.jdbc.samples.entity.Employee;
    import com.oracle.jdbc.samples.bean.EmployeeBean;
    import com.oracle.jdbc.samples.bean.EmployeeBeanImpl;
    import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.BufferedReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.logging.Logger;
    
  2. Add the annotation to the Servlet.
    @WebServlet(name = "WebController", urlPatterns = {"/WebController"})
  3. Declare the WebController class that extends HttpServlet. Initialize jdbcBean of the type JdbcBeanImpl. This will be a global variable and available for all the methods such as reportError(), processRequest(), and doGet() to use.
    
    public class WebController extends HttpServlet {
    	JdbcBean jdbcBean = new JdbcBeanImpl();		
    }
  4. Create the reportError() method to capture and display the error on the web page.
    
    private void reportError(HttpServletResponse response, String message)
    throws ServletException, IOException {
      response.setContentType("text/html;charset=UTF-8"); /*Set the response content type to be “text/html” and charset=UTF-8*/
    
     /*Print the error message*/
     try (PrintWriter out = response.getWriter()) {      
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet WebController</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body>");
        out.println("</html>");
      }
    }
  5. Create the processRequest method to create processes that requests for HTTP GET and POST methods.
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      Gson gson = new Gson();
      List<Employee> employeeList = null;
      
       if ((value = request.getParameter(LOGOUT)) != null) {
        
    /* Get session and then invalidate it */
    
        HttpSession session = request.getSession(false);
        if (request.isRequestedSessionIdValid() && session != null) {
          session.invalidate();
        }
        handleLogOutResponse(request,response);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      }
    else {
       /*Instantiate the employeeList object by invoking getEmployees method of JavaBean*/
        employeeList = jdbcBean.getEmployees();
      }
    
    if(employeeList != null) {
        response.setContentType("application/json");  /*Set the content type to 'application/json' */
     
     /* Invoke the toJson(…) method and convert the employeeList to JSON*/
        gson.toJson(employeeList,
            new TypeToken<ArrayList<Employee>>() {
            }.getType(),
            response.getWriter());
      }
    /*Add an else condition to cover the error scenario when the employeeList is empty*/
    else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
      }
    
    }
  6. Create the handleLogOutResponse(request, response) method to edit the cookie information when a user is logging out of the application.
    
    private void handleLogOutResponse(HttpServletRequest request, HttpServletResponse response) {
      Cookie[] cookies = request.getCookies();
      for (Cookie cookie : cookies) {
        cookie.setMaxAge(0);
        cookie.setValue(null);
        cookie.setPath("/");
        response.addCookie(cookie);
      }
    }
  7. Create the doGet method to get the employee details from the database and show the results in JSON. JSON will be the output format of the results that is shown on the HTML.
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      processRequest(request, response);
    }
  8. Create the getServletInfo method to display generic information about the servlet.
    
    public String getServletInfo() {  
      return "JdbcWebServlet: Reading Employees table using JDBC and transforming it as a JSON.";
    }