BaseServlet - servlet optimization

BaseServlet - servlet optimization

servlet role

​ Generally speaking, servlet is specially used to receive the client's request, specifically to receive the client's request data, and then call the underlying service to process the data and generate the result

The traditional way of writing servlet s

​ As you can see from the picture, we only have two classes, one user class and one task class, and the functions are very simple, log in and register, add and modify query tasks, and there are already five servlet s, so we will have one in the future. If a servlet function is used, it will be very redundant, and the servlets of the user and the task are written together, so it is difficult to distinguish what is what, which increases the difficulty of post-maintenance.

Optimization ideas

MVC three-tier architecture

​ Then can we design an easy-to-manage method for unified management?

​ Refer to the service and dao layers in our MVC three-tier architecture

Let's try to be like them, a specific class is managed by a corresponding dao or service class. We designed BaseServlet. Does it feel much clearer?

​ Then the function in each module is abstracted into a method. (The picture shows the method in UserServlet)

​ Then our front-end request path is written like this

servlet running process

​ The client sends a request—init initializes the servlet—calls the service method to automatically identify the post or get request method. We designed each function as a method above, so how do we automatically identify which method it is? We thought of reflection. Then let's combine the service method and reflection to transform it so that it can automatically identify which method it is.

optimization process

  1. Originally, we directly inherited HttpServlet, but now we have an additional layer of BaseServlet, so our original class should inherit BaseServlet, then BaseServlet inherits HttpServlet, and then rewrites the service method inside.
/*BaseSevlet Inherit HttpServlet*/
public class BaseServlet extends HttpServlet {
 
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        //1. Get the request path first
        String requestUrl = req.getRequestURI();

        //2. Get the last method name of the request path (see the url picture above for details)
        int index = requestUrl.lastIndexOf('/');
        String methodName = requestUrl.substring(index + 1);

        //3. Get the bytecode file of the calling object
        Class<? extends BaseServlet> clazz = this.getClass();
        try {
            //4. Get the method in the class by the method name.
            Method method = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //5. Execution method
            method.invoke(this, req,resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
  1. The original class inherits BaseServlet
/**
 * @program: BaseServlet
 * @description:
 * @author: stop.yc
 * @create: 2022-04-13 15:42
 **/

//Under user, * represents any
@WebServlet("/user/*")
public class UserServlet extends BaseServlet{

    /**
    * @Description: login servlet
    * @Param: [req, resp]
    * @return: void
    * @Author: stop.yc
    * @Date: 2022/4/13
    */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //1. Get the front-end data (post) request body
        BufferedReader reader = req.getReader();
        String userStr = reader.readLine();
          
        //2......
    }
}
  1. Front-end request writing
//It's just an example of url, other codes are according to your code.
axios({
    method: "post",
    url: "http://localhost:8080/qg-engineering-management-system/user/login",
    data: _this.user,
}).then(function (resp) {
    //. . . 
}

Tags: Java Back-end

Posted by yobo on Mon, 09 May 2022 19:01:25 +0300