directory

  1. preface
  2. The Filter Filter
  3. Interceptor Interceptor
  4. The Aspect slice
  5. conclusion

preface

You may have heard of filters, interceptors, and sections, but they can all play a role in blocking interception. When doing some business requirements, I don’t know how to choose. Today, I will introduce the differences between them.

The Filter Filter

A filter can intercept a method’s request and response (ServletRequest Request, ServletResponse Response) and filter the request response.

Filters depend on the servlet container. In implementation, it can filter almost all requests based on function callbacks, and a filter instance can only be called once when the container is initialized.

The purpose of using the filter is to do some filtering operations to obtain the data we want to obtain, such as: modify the character encoding in the filter; Modify some parameters of HttpServletRequest in the filter, including filtering vulgar text, dangerous characters, and so on.

Without further ado, let’s start with the code

Define two controllers, a UserController and an OrderController

Although the Filter Filter and the Controller request are defined, the Filter is now useless. The Filter needs to be configured. There are two solutions

The first scenario adds @Component to Filter

@Component
public class TimeFilter implements Filter
Copy the code

The second scenario configures registration filters

The feature of the second scheme is that you can refine the URL of which rules to filter

When we start the application, the filter is initialized and init function is called back.

requesthttp://localhost:9000/order/1

Take a look at the console’s log output

requesthttp://localhost:9000/user/1

Console Log Output

Console output after stopping the application

The Filter is started when the Web application is started, initialized only once, and destroyed when the Web application is stopped.

1. Load the instance of the filter when starting the server and call init() to initialize the instance;

2. Call doFilter() only for each request;

3. Call destroy() to stop the server and destroy the instance.

Let’s look at the doFilter method

doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

From the parameters, we can see that filter is the data that can get the parameters of the request and the response. But this method does not know which method in which Controller class is being executed.

It is also important to note that there is no way to use injected beans in filter, i.e. @AutoWired

The value injected by the above code is NULL. Why is that?

In Spring, web applications start in the following order: Listener ->filter->servlet initializes the listener, then initializes the filter, and then initializes our dispathServlet. Therefore, when we need to inject an annotated bean into the filter, the injection will fail. Because filter is initialized, the annotated bean is not initialized and cannot be injected.

Interceptor Interceptor

It depends on the Web framework, and in the case of SpringMVC it depends on the SpringMVC framework. In terms of implementation, Java-based reflection is an application of AOP, which calls a method before or after a method.

In WebMvcConfigurationSupport configuration

The execution result

We found that the Controller object is available in the interceptor

preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
Copy the code

Object handler is the controller method object

HandlerMethod handlerMethod = (HandlerMethod)handler; handlerMethod.getBean().getClass().getName(); // Get the class name handlermethod.getMethod ().getName(); // Get the method nameCopy the code

But we can’t get the parameter value of the method. Why is this? In the DispatcherServlet class, method

doDispatch(HttpServletRequest request, HttpServletResponse response)

The applyPreHandle method executes the interceptor’s preHandler method, but the Controller method doesn’t get the request parameters from the request, assembles the method parameters; Instead, the parameters are assembled in the ha.handle method

You can’t get the method’s parameters, but you can get the IOC bean.

One more point is the postHandler method

PostHandler method, when there is an exception inside the controller, postHandler method will not execute.

The afterCompletion method, which executes regardless of whether there is an exception inside the Controller; The method also takes an Exception ex parameter; If there are exceptions, ex will have outliers; No exceptions this value is null

Note that ex is also null if there is an exception inside the controller that is caught by @ControllerAdvice

The Aspect slice

AOP operations can intercept operations horizontally, and the biggest advantage is that they can take the parameters of the execution method and treat the method uniformly. Common uses include logging, transactions, request parameter security verification, etc

In the above code, we can get method parameters

While faceted AOP can get method parameters, it can’t get response or Request objects.

conclusion

Let’s summarize filters, interceptors, and aspects here to see the differences

If all three methods are used together, what is the order in which they are executed?

filter -> interceptor -> ControllerAdvice -> aspect -> controller

Return value order, or exception return order

controller -> aspect -> controllerAdvice -> Interceptor -> Filter

Use a diagram to describe the order of execution

Partners can choose the corresponding technology according to their own business and the respective characteristics of the above technology. That’s all for today, thank you!!

—End—