Use a Servlet to handle all requests

The problem

Writing servlets is an essential part of developing JavaWeb applications, but typically a Servlet handles a specific request. As more servlets are written, managing servlets becomes more and more troublesome.

So how can you reduce the number of servlets? All you need is a Servlet to distribute the request, handing it over to different methods for processing. But methods are stacked in a class that is also difficult to manage, so each class represents a module, and each module has a specific method to handle different requests.

plan

The solution is to use a Servlet to handle all requests, distribute them to the corresponding class and execute the specified method.

implementation

Next comes the implementation of the scenario. How do I forward the request to the specified method? Classes and methods, you can think of using reflection, and most of the front-end to back-end communication is in urIs. So as long as you get the class and method names in the URI, you can process the specified request. Using the IOC container in conjunction with Spring, the corresponding instance is obtained.

code

@WebServlet(urlPatterns = "*.do",name = "MyDispatcherServlet")
public class MyDispatcherServlet extends HttpServlet {

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        ApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(this.getServletContext());

        String requestURI = req.getRequestURI();
        requestURI = requestURI.substring(0, requestURI.indexOf(".do"));
        System.out.println(requestURI);
        ///myServlet/course/test.do"

        // Split the URI into an array
        / / such as URI = / myServlet/course/test -- -- -- - > [", "" myServlet", "course", "test"]
        //split[0] and split[1] are fixed,split[2] represents the desired instance, and split[3] is the method to be executed in the instance
        String[] split = requestURI.split("/");


        // Get the instance from the IOC container
        Object bean = context.getBean(split[2]);
        // Get the class objectClass<? > aClass = bean.getClass();try {
            Use reflection to get the specified method of the class object
            Method method = aClass.getMethod(split[3], HttpServletRequest.class, HttpServletResponse.class);
            // Execute the specified method in the instance
            method.invoke(bean, req, resp);

        } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); }}}Copy the code

This is a demo implementation that uses only one Servlet to handle requests