In the actual project development process, there must be such requirements:

  1. Record the time spent on each REST request, incoming and outgoing parameters
  2. Some requests need to be determined whether they have permission, and some requests can be run without permission

This need is all too common. Today we’ll look at two ways to implement this requirement:

  1. The interceptor
  2. The filter

The interceptor

Without further comment, let’s add the code and create a new log interceptor:

@Component public class LogInterceptor implements HandlerInterceptor {// Override public Boolean is called before requesting the REST interface preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println(" RequestURL: "+request.getRequestURL()); Map<String, String[]> parameterMap = request.getParameterMap(); Enumeration<String> parameterNames = request.getParameterNames(); System.out.println(" Request parameters: "); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); String value = request.getParameter(name); System.out.println(name+"==>"+value); } if("1".equals(request.getParameter("a")) {return false; } return true; // If false is returned it will not proceed and will not actually enter the controller} // The call will be made after the request has been processed. Override public void posHandle (HttpServletRequest request, HttpServletResponse response, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle is called..." ); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion is called..." ); }}

Register the interceptor with the WebMVCConfiguring urer and tell Spring which paths to block and which paths not to block

@Configuration public class InterceperConfig implements WebMvcConfigurer { @Override public void AddInterceptors (InterceptorRegistry Registry) {// add InterceptorRegistration InterceptorRegistration = registry.addInterceptor(new LogInterceptor() { }); / / the following the path of the intercept, multiple paths separated by commas interceptorRegistration. ExcludePathPatterns ("/demo/test2 "); . / / intercept the following path interceptorRegistration addPathPatterns (" / * * "); }}

Okay, so the interceptor is done. Let’s write a controller to test it.

@RestController @RequestMapping("/demo") public class DemoController { @GetMapping("test1") public String test1(){ System.out.println("rest.test1 is called"); return "test1"; } @GetMapping("test2") public String test2(){ System.out.println("rest.test2 is called"); return "test2"; } @GetMapping("test3") public String test3(@RequestParam("a")String a){ System.out.println("rest.test3 is called"); return "test3"; }}

The results of the test were largely predictable

  1. Demo /test1 and demo/test3 will be intercepted, into interceptors
  2. Demo /test2 will not use interceptors
  3. demo/test3? A =1 The request will go into the interceptor, but not into the controller.

The filter

@WebFilter(urlPatterns = "/*", filterName = "LogFilter") public class LogFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("logfilter.init is called..." ); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, Throws IOException, ServletException {System.out.println(" Filter printed request parameters: "); Enumeration<String> parameterNames = servletRequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String key = parameterNames.nextElement(); String value = servletRequest.getParameter(key); System.out.println(key+"==>"+value); } long bgn = System.currentTimeMillis(); / / must call chain call transfer, otherwise it couldn't get into the controller filterChain. DoFilter (servletRequest, servletResponse); long end = System.currentTimeMillis(); System.out.println(" Filter time: "+(end-bgn)+"ms"); } @Override public void destroy() { System.out.println("logfilter.destroy is called..." ); }}

Note:
@WebFilterThis comment is
Servlet3.0It’s not
Spring bootProvide. In addition to this annotation, we need to add another annotation to the configuration class:
@ServletComponetScan, which specifies the package to scan.

conclusion

Interceptor and filter execution order, the default filter is executed first, then the interceptor.

If there are more than one filter, it will be executed in order of A-Z according to the name of the filter. This is because the @WebFilter annotation does not support execution order. Of course you can also write a configuration file to solve this problem.

@Configuration public class WebConfig { @Bean public FilterRegistrationBean reqResFilter1() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); LogFilter logFilter = new LogFilter(); filterRegistrationBean.setFilter(logFilter); filterRegistrationBean.addUrlPatterns("/demo/test1","/demo/test3"); / / configuration filter rules filterRegistrationBean. AddInitParameter (" name ", "spingboot"); / / set the init parameter filterRegistrationBean. Elegantly-named setName (" logFilter "); / / set the filter name filterRegistrationBean setOrder (2); Return FilterRegistrationBean; } @Bean public FilterRegistrationBean reqResFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); Log1Filter log1Filter = new Log1Filter(); filterRegistrationBean.setFilter(log1Filter); filterRegistrationBean.addUrlPatterns("*"); / / configuration filter rules filterRegistrationBean. Elegantly-named setName (" Log1Filter "); / / set the filter name filterRegistrationBean. SetOrder (1); Return FilterRegistrationBean; }}

Read more about Java:
https://javawu.com/