Java extraction Servlet (optimized)

Posted by web_master on Sat, 08 Jan 2022 05:38:40 +0100

Problem analysis: when we write servlets, a function will correspond to a Servlet, such as LoginServlet and RegisterServlet corresponding to login and registration. When a management system has many functions, there will be 10-30 servlets, which will be very messy when people look at the code

The purpose of extracting servlets: reduce the number of files of servlets, classify servlets according to entities, increase the readability of code and reduce the coupling degree of code

Steps:

1. Create a basic Servlet and call the corresponding function method of the corresponding Servlet through reflection

2. Create the required entity servlets. Each entity Servlet inherits the BasicServlet and defines all the function methods of the entity

The BasicServlet is as follows:

/*
    Basic Servlet
 */
public class BasicServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName =  req.getParameter("method");
        //If the Servlet chooses to redirect or forward, the method will return a non null string
        if(methodName != null){
            try {
                //reflex
                Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
                //Call the method corresponding to the method name
                Object actionObj =  method.invoke(this,req,resp);
                if(actionObj != null){
                    String action = actionObj.toString();
                    if(action.startsWith("redirect:")){
                        System.out.println(action.split("redirect:")[1]);
                        //redirect
                        resp.sendRedirect(action.split("redirect:")[1]);

                    }else{
                        //forward
                        req.getRequestDispatcher(action);
                    }
                }else{
                    System.out.println("empty");
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

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

A UserServlet is written here as an example. The template is as follows:

@WebServlet("/user")
public class UserServlet extends BasicServlet {

    public String login(HttpServletRequest request,HttpServletResponse response){
        /*        
            Omitted here, write business code according to requirements
         */
        
        //Redirect index jsp
        return "redirect:index.jsp";
    }

    public String register(HttpServletRequest request,HttpServletResponse response){
         /*        
            Omitted here, write business code according to requirements
         */

        //Forward login jsp
        return "login.jsp";
    }
}

login. The JSP example is as follows, focusing on the request path sent by action

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
<center>This is the landing page</center>
<form action="user?method=login" method="post">
    <span>user name:</span><input name="username">
    <div><input type="submit" value="Submit"></div>
</form>
</body>
</html>

Some readers may have the following questions ❔:

1) Why isn't BasicServlet registered as a WebServlet?

BasicServlet is used to determine the specific requested function (login, registration, etc.) and jump direction (forwarding or redirection) of each WebServlet, then use reflection to call the corresponding function method of WebServlet, and use the if branch for redirection or forwarding. WebServlet only needs to focus on the specific business code of function implementation, so as to reduce the code coupling as a whole!

2) Why not write DoGet and DoPost methods in WebServlet, but write these two methods in BasciServlet?

First clarify the inheritance system above, which is UserServlet - > BasicServlet - > httpservlet. Although UserServlet is registered as WebServlet, it does not have DoGet or DoPost methods, then it will call the DoGet or DoPost method of the parent class, that is, BasicServlet, and then call the function method corresponding to WebServlet through the parent class.

In this way, there is no need to write DoGet or DoGet methods in each WebServlet, so as to reduce the coupling degree of the code.

Note: in the above answer, the WebServlet I mentioned refers to the specific class registered as a Servlet in Tomcat, which is the entry of user requests.

If you think this article has some inspiration and help for you, or if you are a great God passing by, you can praise it 💖+ follow 😋. Make progress with you in 2022 💪

Topics: Java Apache Back-end servlet server