This article is in Java Server, which contains my entire Series of Java articles for study or interview

(a) what is a filter

The Filter is implemented based on servlets. The Filter is mainly applied to Filter character encoding and cross-domain problems. Servlets work by intercepting configured client requests and then processing Request and Response. The Filter is started with the start of the Web application and is initialized only once.

Filter is easy to use. Inherit the Filter interface and implement the corresponding init, doFilter, and destroy methods.

Init: Call the initialization method when the container is started. It will be initialized only once

2. DoFilter: The doFilter method is invoked on each request and subsequent methods are called through FilterChain

3, destroy: When the container is destroyed, the destory method is called only once.

Here’s how the code is written in detail:

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Initialize interceptor");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Do some processing
        chain.doFilter(request,response);
    }

    @Override
    public void destroy(a) {
        System.out.println("Destroy the interceptor."); }}Copy the code

(II) What is an interceptor

Interceptor is a method enhancement tool based on Java reflection (dynamic proxy) mechanism implemented in SpringMVC. The implementation of interceptor inherits the HandlerInterceptor interface and implements its preHandle, postHandle and afterCompletion methods.

1, preHandle: Spring can have multiple interceptors. These interceptors are called in Order. When one of the interceptors returns false in the preHandle, the request is terminated.

PostHandle: Called after Controller method execution but before view rendering when preHandle returns true

AfterCompletion: Execute the method after the preHandle returns true and the entire request is complete.

The specific code implementation is as follows, first write an interceptor:

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        String userName=request.getParameter("userName");
        String password = request.getParameter("password");
        if (userName==null||password==null){
            response.setStatus(500);
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().print("Parameter missing");
            return false;
        }
        // Perform user verification
        if (userName.equals("admin")&&password.equals("admin")) {return true;
        }else {
            response.setStatus(500);
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().print("Wrong username or password");
            return false; }}@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion"); }}Copy the code

Once you’ve written the interceptor, you set it up with a configuration class, and you can use addPathPatterns and excludePathPatterns to enforce which requests need to be blocked and which don’t.

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Autowired
    private UserInterceptor userInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userInterceptor)
                .addPathPatterns("/ * *")
                .excludePathPatterns("/error"); }}Copy the code

(iii) the difference between interceptor and filter

Similarities:

1. Interceptors and filters embody the idea of AOP and can be enhanced to intercept request methods.

2. Interceptors and filters can be ordered using the Order annotation

Difference:

Filters are defined in the Javax. Servlet package and depend on the network container, so they can only be used in Web projects.

Interceptor is implemented in SpringMVC, and the root Interceptor is a Spring component managed by the Spring container.

2. Filters and interceptors are executed in different order:

The following diagram shows the execution order of Filter and Interceprtor

First, the filter’s doFilter method filters a request before it enters the Servlet.

After entering the Servlet container and before executing the Controller method, the interceptor’s preHandle method intercepts,

After executing the Controller method and before rendering the view, the interceptor’s postHandle method intercepts,

After the request completes, the interceptor’s postHandle method is executed.

3. Filters are implemented based on function callbacks and interceptors are implemented based on Java reflection mechanism

(4) Summary

In practice, interceptors are used in more scenarios than filters. Here are the main application scenarios for interceptors and filters

Application scenarios of interceptor: permission control, log printing, parameter verification

Application scenarios of filters: cross – domain problem solving, code conversion

I looked at the code for historical projects and found that interceptors are used more often in user permission verification scenarios, but filters are used less often because they are typically separated from the front and back.

Interceptor and filter are more commonly used, but still have to pay attention to the gap between the two, I am fish, we will see you next time!