Spring Boot using filters and interceptors

Filter (the Filter) and the interceptor (Interceptor) is commonly used Web project two functions, article briefly describes the use of filters and interceptor Spring Boot Controller performed to calculate the duration of the method, and a simple comparison of both the difference.

Existing follows Controller:

@RestController
@RequestMapping("user")
public class UserController {

  @GetMapping("/{id:\\d+}")
  public void get(@PathVariable String id) {
      System.out.println(id);
  }
}

 

The following is achieved by the configuration of the filter and the interceptor get method execution time calculation function.

filter

Define a TimeFilter class that implements the javax.servlet.Filter :

public class TimeFilter implements Filter{
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
      System.out.println("过滤器初始化");
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      System.out.println("开始执行过滤器");
      Long start = new Date().getTime();
      filterChain.doFilter(servletRequest, servletResponse);
      System.out.println("【过滤器】耗时 " + (new Date().getTime() - start));
      System.out.println("结束执行过滤器");
  }

  @Override
  public void destroy() {
      System.out.println ( "Filter Destruction");
  }
}

 

TimeFilter rewrite Filter three methods, the method has been very straightforward name describes its role, not repeat them here.

To make the filter effect Spring Boot, the need some configurations. There are two main configurations.

A configuration

It can be prepared by TimeFilter adding annotations on the following:

@Component
@WebFilter(urlPatterns = {"/*"})
public class TimeFilter implements Filter {
  ...
}

 

@Component annotation lets TimeFilter become a Bean Spring context, @WebFilter annotation urlPatterns property configuration which can request access to the filter, / * represents all requests.

When you start the project you can see the console output filter is initialized , access the start HTTP: // localhost: 8080 / the User / 1 , the console output is as follows:

Started filters 
1
[filter] took 31
ends the execution of filter

 

Second way configuration

Except as noted on the filter class, we can also FilterRegistrationBean to register the filter.

Define a WebConfig class, plus @Configuration comment indicating that the configuration of the class, then FilterRegistrationBean register Filter:

@Configuration
public class WebConfig {
  @Bean
  public FilterRegistrationBean timeFilter() {
      FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
      TimeFilter timeFilter = new TimeFilter();
      filterRegistrationBean.setFilter(timeFilter);

      List<String> urlList = new ArrayList<>();
      urlList.add("/*");

      filterRegistrationBean.setUrlPatterns(urlList);
      return filterRegistrationBean;
  }
}

 

FilterRegistrationBean addition to registering the filter TimeFilter outside through setUrlPatterns arranged URL matching rules method. Access to restart the project HTTP: // localhost: 8080 / the User / 1 , we can see the same effect as above.

We can only get to servletRequest objects through the filter, and therefore it can not obtain additional information to the name of the method, belongs to the class, and other parameters.

Interceptor

Define a TimeInterceptor class that implements org.springframework.web.servlet.HandlerInterceptor Interface:

public class TimeInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
      System.out.println("处理拦截之前");
      httpServletRequest.setAttribute("startTime", new Date().getTime());
      System.out.println(((HandlerMethod) o).getBean().getClass().getName());
      System.out.println(((HandlerMethod) o).getMethod().getName());
      return true;
  }

  @Override
  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
      System.out.println ( "start processing knockdown");
      Long Start = (Long) httpServletRequest.getAttribute ( "the startTime");
      System.out.println ( "[] Processed interceptor" + (new Date () getTime . () - Start));
  }   @Override   public void afterCompletion (the HttpServletRequest HttpServletRequest, HttpServletResponse the HttpServletResponse, Object O, Exception E) throws Exception {       System.out.println ( "knockdown after treatment");       Long Start = (Long) HttpServletRequest .getAttribute ( "the startTime");       System.out.println ( "[] Processed interceptor" + (new new a Date () the getTime () - Start).);       System.out.println ( "exception information" + e) ;   } }








 

TimeInterceptor realized HandlerInterceptor three interface methods. preHandle method to intercept execution before processing, postHandle only if the method successfully intercepted an exception handling will not throw, afterCompletion method regardless of the method intercepted an exception is thrown or not will be executed.

Parameters can be seen through these three methods, compared to filters, interceptors and more Object Exception object, so the information can be retrieved much more than a filter. But still can not get to the filter parameter information and other methods, we can achieve this through section programming, specifically refer to https://mrbird.cc/Spring-Boot-AOP%20log.html .

To effect Spring Boot interceptor, the configuration needs two steps as follows:

1. Add the interceptor class @Component annotation;

2. WebConfig by InterceptorRegistry filter registration:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
  @Autowired
  private TimeInterceptor timeInterceptor;

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

 

Start the project, visit HTTP: // localhost: 8080 / the User / 1 , the console output is as follows:

Before treatment interception 
cc.mrbird.controller.UserController
GET
1
start processing interceptors
[interceptor] consuming 24
after processing interceptors
[interceptor] took 24
anomalies null

 

From the output we can see that the order of execution of the three methods, and three methods are executed.

We UserController 's get the manual method throws an exception:

 @GetMapping("/{id:\\d+}")
public void get(@PathVariable String id) {
  System.out.println(id);
  throw new RuntimeException("user not exist");
}

 

After restarting the project, visit HTTP: // localhost: 8080 / the User / 1 , the console output is as follows:

Before treatment interception 
cc.mrbird.controller.UserController
GET
1
after processing interceptors
[interceptor] 0 takes
exception information java.lang.RuntimeException: user not exist

 

It can be seen, postHandle method has not been implemented.

Execution timing comparison

We will filter and interceptors are configured, and then start the project visit HTTP: // localhost: 8080 / the User / 1 :

Started filters 
before processing intercept
cc.mrbird.controller.UserController
GET
1
start processing interceptors
[interceptor] took 25
after processing interceptors
[interceptor] took 25
Information null abnormal
[filter] takes 34
to perform filter end

 

Filters can be seen in the first interceptor executed later than the end of the interceptor. Well described under FIG their execution time difference:

Guess you like

Origin www.cnblogs.com/7788IT/p/11626850.html