Three ways to intercept requests Filter, Interceptor, Aspect

In java web development, we can intercept requests in three ways: Filter, Interceptor, and Aspect. Let's introduce the similarities and differences between these three ways.

Take a simple spring-boot project as an example to record the execution time of the Controller method.

Project structure

HelloController

@RestController
public class HelloController {

    @GetMapping("/hello")
    public Object sayHello(String name) {
        System.out.println("name: " + name);
        return "hello " + name;
    }

}

unit test

Write a unit test first to verify the correctness of the HelloController.sayHello() method.

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void sayHello() throws Exception {
        // 模拟 get 请求
        mockMvc.perform(
                get("/hello") // get 请求 url /hello
                        .param("name", "tom") // 参数 name=tom
                        .contentType(MediaType.APPLICATION_JSON_UTF8)) // 设置请求头 Content-Type = application/json;charset=UTF-8
                .andExpect(status().isOk()) // 期望返回的状态码为200
                .andExpect(content().string("hello tom")); // 期望返回值为"hello tom"
    }

}

After testing, HelloController.sayHello() has no problem.

Filter

New TimeFilter

@Component
public class TimeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("time filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("time filter start");
        long startTime = System.currentTimeMillis();

        filterChain.doFilter(servletRequest, servletResponse);

        long endTime = System.currentTimeMillis();
        System.out.println("time filter consume " + (endTime - startTime) + " ms");
        System.out.println("time filter end");
    }

    @Override
    public void destroy() {
        System.out.println("time filter init");
    }
}

Start the server and enter in the browser: http://localhost:8080/hello?name=tomYou can output the following results in the console:

time filter start
name: tom
time filter consume 3 ms
time filter end

As you can see, the filter is executed first, and then the HelloController.sayHello() method is actually executed.

From the parameters of the TimeFilter.doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) method, we can see that we can only get the original request and response objects, but cannot get which Controller and which method the request was processed by, we can get it by using Interceptor these messages.

Interceptor

New TimeInterceptor

@Component
public class TimeInterceptor extends HandlerInterceptorAdapter {

    private final NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("startTimeThreadLocal");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("time interceptor preHandle");

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取处理当前请求的 handler 信息
        System.out.println("handler 类:" + handlerMethod.getBeanType().getName());
        System.out.println("handler 方法:" + handlerMethod.getMethod().getName());
        
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        for (MethodParameter methodParameter : methodParameters) {
            String parameterName = methodParameter.getParameterName();
            // 只能获取参数的名称,不能获取到参数的值
            //System.out.println("parameterName: " + parameterName);
        }

        // 把当前时间放入 threadLocal
        startTimeThreadLocal.set(System.currentTimeMillis());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("time interceptor postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 从 threadLocal 取出刚才存入的 startTime
        Long startTime = startTimeThreadLocal.get();
        long endTime = System.currentTimeMillis();

        System.out.println("time interceptor consume " + (endTime - startTime) + " ms");

        System.out.println("time interceptor afterCompletion");
    }
}

Register TimeInterceptor

Inject TimeInterceptor into the spring container

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private TimeInterceptor timeInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }
}

Start the server and enter in the browser: http://localhost:8080/hello?name=tomYou can output the following results in the console:

time filter start
time interceptor preHandle
handler 类:com.nextyu.demo.web.controller.HelloController
handler 方法:sayHello
name: tom
time interceptor postHandle
time interceptor consume 40 ms
time interceptor afterCompletion
time filter consume 51 ms
time filter end

As you can see, the filter is executed before the interceptor, and then the HelloController.sayHello() method is actually executed.

Through the handler parameter on the interceptor method, we can get which Controller and which method the request is handled by. But the parameter value of this method cannot be directly obtained (here is the value of the parameter name of the HelloController.sayHello(String name) method), it can be obtained through Aspect.

Aspcet

New TimeAspect

@Aspect
@Component
public class TimeAspect {

    @Around("execution(* com.nextyu.demo.web.controller.*.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {

        System.out.println("time aspect start");

        Object[] args = pjp.getArgs();
        for (Object arg : args) {
            System.out.println("arg is " + arg);
        }

        long startTime = System.currentTimeMillis();

        Object object = pjp.proceed();

        long endTime = System.currentTimeMillis();
        System.out.println("time aspect consume " + (endTime - startTime) + " ms");

        System.out.println("time aspect end");

        return object;
    }

}

Start the server and enter in the browser: http://localhost:8080/hello?name=tomYou can output the following results in the console:

time filter start
time interceptor preHandle
handler 类:com.nextyu.demo.web.controller.HelloController
handler 方法:sayHello
time aspect start
arg is tom
name: tom
time aspect consume 0 ms
time aspect end
time interceptor postHandle
time interceptor consume 2 ms
time interceptor afterCompletion
time filter consume 4 ms
time filter end

It can be seen that the filter is executed first, then the interceptor is executed, then the aspect is executed, and then the HelloController.sayHello() method is actually executed.

We also get the value of the parameter name of the HelloController.sayHello(String name) method.

Request interception process diagram

Summarize

  • Filter is in the java web, and definitely can't get the information of the Controller in spring.
  • Interceptor and Aspect are related to spring, so the information of Controller can be obtained.

Source address

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325458340&siteId=291194637