Using Web frameworks at work, you can't avoid dealing with these concepts, do a summary, and say interceptors, filters, and listeners in one go.
Listener > Filter > Interceptor
[Note] The following code is based on springboot2.0
(1) Interceptor
MyInterceptor1 inherits HandlerInterceptorAdapter
MyInterceptor2 implements the HandlerInterceptor interface
public class MyInterceptor1 extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setAttribute("startTime", System.currentTimeMillis());
System.out.println(">>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>");
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long startTime = (long) request.getAttribute("startTime");
System.out.println("MyInterceptor1 Execution:" + (System.currentTimeMillis() - startTime));
System.out.println(">>>>> MyInterceptor1 postHandle >>>>>>>>>>>>>>>>>>>>>>");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
request.removeAttribute("startTime");
System.out.println(">>>>> MyInterceptor1 afterCompletion >>>>>>>>>>>>>>>>>>>>>>");
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
super.afterConcurrentHandlingStarted(request, response, handler);
System.out.println(">>>>> MyInterceptor1 afterConcurrentHandlingStarted >>>>>>>>>>>>>>>>>>>>>>");
}
}
public class MyInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setAttribute("startTime", System.currentTimeMillis());
System.out.println(">>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long startTime = (long) request.getAttribute("startTime");
System.out.println("MyInterceptor2 Execution:" + (System.currentTimeMillis() - startTime));
System.out.println(">>>>> MyInterceptor2 postHandle >>>>>>>>>>>>>>>>>>>>>>");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
request.removeAttribute("startTime");
System.out.println(">>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>>>>>>>");
}
}
(2) Configuration
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
}
}
(3) Request
@RestController
@SpringBootApplication
public class SpringbootInterceptorApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootInterceptorApplication.class, args);
}
@GetMapping(value = "/hello1")
public ResponseEntity<String> hello() throws InterruptedException {
Thread.sleep(500);
return ResponseEntity.ok("HelloWorld");
}
@GetMapping(value = "/hello2")
public StreamingResponseBody hello2() throws InterruptedException {
Thread.sleep(500);
return (OutputStream outputStream) -> {
outputStream.write("success".getBytes());
outputStream.flush();
outputStream.close();
};
}
@GetMapping(value = "/hello3")
public Future<String> hello3() throws InterruptedException {
Thread.sleep(500);
return new AsyncResult<>("Hello");
}
}
(4) Operation results
Request /hello1
>>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>
MyInterceptor2 execution: 516
>>>>> MyInterceptor2 postHandle >>>>>>>>>>>>>>>>>>>>>
MyInterceptor1 execution: 516
>>>>> MyInterceptor1 postHandle >>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>
>>>>> MyInterceptor1 afterCompletion >>>>>>>>>>>>>>>>
Execute by pressing preHandle > postHandle > afterCompletion
Request /hello2 or /hello3
>>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor1 afterConcurrentHandlingStarted >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor1 preHandle >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor2 preHandle >>>>>>>>>>>>>>>>>>>>>>
MyInterceptor2 execution: 1
>>>>> MyInterceptor2 postHandle >>>>>>>>>>>>>>>>>>>>>>
MyInterceptor1 execution: 1
>>>>> MyInterceptor1 postHandle >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>>>>>>>
>>>>> MyInterceptor1 afterCompletion >>>>>>>>>>>>>>>>>>>>>>
MyInterceptor1 execution order preHandle > afterConcurrentHandlingStarted > preHandle > postHandle >afterCompletion
MyInterceptor2 execution order preHandle > preHandle > postHandle > afterCompletion
In summary. For the return value of the concurrent type, spring will enable a new thread to handle the concurrent type message, and the preHandle method will be called again in the new thread.
(1) Filter
public class MyFilter1 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(filterConfig.getInitParameter("initParam"));
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter1 >>>>>>>>>>>");
filterChain.doFilter(servletRequest, servletResponse);
}
}
(2) Configuration
@Bean
public FilterRegistrationBean<MyFilter1> filterRegistrationBean() {
FilterRegistrationBean<MyFilter1> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.addUrlPatterns("/*");//Filter all
filterRegistrationBean.setFilter(new MyFilter1());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.addInitParameter("initParam", "initOk");
return filterRegistrationBean;
}
@Bean
public MyFilter1 myFilter() {
return new MyFilter1();
}
@WebFilter("/test/*")
public class MyFilter2 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("MyFilter2");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("DoFilter 2");
}
}
By @WebFilter("/test/*") annotation, you first need @ServletComponentScan("com.jiuxian")
Filter global interception configuration (/*) and Interceptor (/**) are different need to pay attention
(1) Listener
public class MyListener1 implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("MyListener1 ... ");
}
}
(2) Configuration mode is similar to Filter
@Bean
public ServletListenerRegistrationBean<MyListener1> registrationBean() {
ServletListenerRegistrationBean<MyListener1> servletListenerRegistrationBean
= new ServletListenerRegistrationBean<>();
servletListenerRegistrationBean.setListener(new MyListener1());
return servletListenerRegistrationBean;
}
@Bean
public MyListener1 myListener1() {
return new MyListener1();
}
@WebListener
public class MyListener2 implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("MyListener2");
}
}
To use the @WebListener annotation, you first need @ServletComponentScan("com.jiuxian")
[Note] The above code is based on springboot2.0
User authentication and authorization, logging MDC, codec, UA check, multi-end correspondence, etc. all need to be handled by interception request. In this case, Filter, Listener and Interceptor are r...
One: Filter Declare the filter and use the @ServletComponentScan annotation in Application Two: Listener 1. ServletContextListener The contextInitialized() method is executed when the application star...
pom.xml application.properties index.html Application.java filter MyFilter.java interceptor WebAppConfig.java MyInterceptor.java MyHandlerInterceptorAdapter.java listener MyServ...
Foreword We need to add annotations @ServletComponentscan on Spring-Boot startup before writing filters, listeners, and interceptors. Servlet Spring-boot write filters and Spring is similar, direct vi...
I. Introduction Web.xml has been removed in Spring Boot, if you need to register Add servlet, filter, listener is Spring Bean, there are two ways in Spring Boot: Use the Servlet 3.0 API @ WebServlet, ...
filter(Filter)withListener (Listener)'S registration method andServlet Similarly, if you are unclear, you can check the previous article.This article will be used directly@WebFilterwith@WebListen...
First, the order of HTTP request background execution Start sequence: listener> filter> interceptor (context-param-->listener-->filter-->servlet-->interceptor) Memory skills: Receive...
background: In fact, it is necessary to complete a simple security verification of the calling interface. It seems that it is relatively easy to find out the signature algorithm. After all, the hmac a...
Filter FILTER is part of the servlet container, part of the Servlet specification, The interceptor is independent, which can be used in any case. Article catalog Filter filter FilterRegistrationBean m...
1. Filter In fact, the filter (Filter) is very similar to Servlet, which is a component of Java. That is, before sending to Servlet, you can intercept and process the request, or you can deal with the...