interceptor

add an interceptor in Spring Boot

Introduction

Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sofisticated behaviour because can access to all Spring context.


Define Spring Boot Filter Interceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TestInterceptor implements HandlerInterceptor {

private final Logger logger = LoggerFactory.getLogger(TestInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("TestInterceptor preHandle controller 执行之前");
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.info("TestInterceptor postHandle controller 执行之后,渲染视图之前");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.info("TestInterceptor afterCompletion 渲染视图之后");
}
}

Register the custom Interceptor

1
2
3
4
5
6
7
8
9
10
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {

TestInterceptor testInterceptor = new TestInterceptor();
registry.addInterceptor(testInterceptor).addPathPatterns("/test/**");
}
}

filter vs interceptor


  spring
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×