[Twenty-two] Springboot integrates interceptors in practice and compares filters
[Twenty-two] Springboot integrates interceptors in practice and compares filters
Exchange entrance addresses with each other
Overall catalog:
[1] springboot integrates swagger
[2] springboot integrates custom swagger
【3】springboot integration token
【4】springboot integrates mybatis-plus
[5] springboot integrates mybatis-plus
【6】springboot integrates redis
[7] springboot integrates AOP to implement log operations
[8] springboot integrates scheduled tasks
[9] Springboot integrates redis to save hotspot data in the global and cache when starting the service
[10] springboot integrates quartz to optimize scheduled tasks
[11] Springboot integrates asynchronous calls and obtains return values
【12】springboot integrates WebService
[13] springboot integrates WebService about passing parameters
【14】springboot integrates WebSocket
【15】springboot integrates WebSocket to implement chat room
[Sixteen] Basics of RabbitMQ (download, install and use it basically, including various pitfalls)
[Seventeen] Basics of RabbitMQ (Practical Combat of Delay Queue and Dead Letter Queue)
[18] Springboot implements custom global exception handling
[19] Beginners to learn Kafka and actually integrate SpringCloudStream for use
[20] Springboot integrates ElasticSearch in practice (10,000 words)
[Twenty-one] Springboot integrated filter practice
[Twenty-two] Springboot integrates interceptors in practice and compares filters
[Twenty-three] Springboot integration activiti7 (1) practical demonstration
[Twenty-four] Detailed explanation and practical implementation of spring boot integration of spring affairs
[25] springboot uses EasyExcel and thread pool to implement multi-threaded import of Excel data
[26] springboot integrates jedis and redisson bloom filters to handle cache penetration
[Twenty-seven] springboot implements multi-threaded transaction processing
[Twenty-eight] springboot's threadLocal parameter parser implements the same session-like saving of the current login function
[Twenty-nine] springboot integrates logback to implement log management
[Thirty] Examples of high concurrency solutions for springboot projects
Table of contents
1. Common interface access
2. Add an interceptor
3. Add three interceptors
4. Compare interceptors and filters
Compared with the previous chapter, this chapter simulates token verification by using interceptors, and then compares the differences between the two. Let’s start learning the basic usage of interceptors.
1. Common interface access
Create two new test interfaces to compare and test whether the interceptor passes. The previous chapter has been built.
Test access, can be accessed normally.
2. Add an interceptor
Next, add interceptor processing to the interface.
Like filters, it is divided into two steps. Firstcreate a custom interceptor , and then register the custom interceptor with the interceptor register.
1. Custom interceptor
2.
3. import org.springframework.lang.Nullable;
4. import org.springframework.stereotype.Component;
5. import org.springframework.web.servlet.HandlerInterceptor;
6. import org.springframework.web.servlet.ModelAndView;
7.
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10.
11. /**
12. * @Classname TestIntercepter
13. * @Description TODO
14. * @Date 2022/4/12 9:03
15. * @Created by zrc
16. */
17. // Customize the interceptor by implementing the HandlerInterceptor interface and overriding its three methods. His three methods are the ones modified by the default keyword to have a default implementation.
18. @Component
19. public class TestInterceptor implements HandlerInterceptor {
20.
21. @Override
22. //Execute the operation before sending the request to the controller controller, if it returns true it will enter the controller, if it returns false it will not enter the controller anymore
23. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
24. String token = request.getHeader("token");; System.out
25. System.out.println("Custom Interceptor 1----- start intercepting, before entering the controller, the interceptor to intercept the request, intercepted the value of the token:" + token);; return null !
26. return null ! = token.
27. }
28.
29. @Override
30. // Used to perform the operation before the response is sent to the client, that is, when the data is returned after the controller is executed.
31. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
32. System.out.println("Custom Interceptor 1 ----- controller execution completed, returning data");;
33. }
34.
35. @Override
36. //Execute the operation after completing the request and response
37. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
38. System.out.println("Custom Interceptor 1 ----- response end");;
39. }
40.
41. }
Customize the interceptor class to implement interception control by implementing the HandlerInterceptor interface and rewriting its three methods, preHandle, postHandle, and afterCompletion.
- preHandle: Execute the operation before sending the request to the controller. If it returns true, it will enter the controller. If it returns false, it will not enter the controller.
- postHandle: used to perform operations before sending the response to the client, that is, when the data is returned after the controller is executed.
- afterCompletion: Execute the operation after completing the request and response.
The above code intercepts the request before it reaches the controller and judges the token in the request. If it is empty, it returns false and it will not enter the controller.
2. Register a custom interceptor
2.
3. import org.springframework.context.annotation.Configuration;
4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
6.
7. import javax.annotation.Resource;
8.
9. /**
10. * @Classname TestIntercepterConfig
11. * @Description TODO
12. * @Date 2022/4/12 9:02
13. * @Created by zrc
14. */
15. // Older versions do this by inheriting the WebMvcConfigurerAdapter class, newer versions do it by implementing the WebMvcConfigurer interface.
16. @Configuration
17. public class TestInterceptorConfig implements WebMvcConfigurer {
18.
19. // Introduce a custom interceptor object
20. @Resource
21. private TestIntercepter testIntercepter;
22.
23. //Introduce custom interceptor object
24. @Resource
25. private TestIntercepter2 testIntercepter2;
26.
27. @Override
28. // Override addInterceptors method to register interceptors
29. public void addInterceptors(InterceptorRegistry registry){
30. //addInterceptor method to the interceptor registry to add interceptors, addPathPatterns method to add intercept path matching rules ("/**" is to intercept all), excludePathPatterns method is to set up a whitelist, which paths are released
31. registry.addInterceptor(testInterceptor).addPathPatterns("/**").excludePathPatterns("/userController/*").order(1); 32. // registry.addInterceptor(testInterceptor).addPathPatterns("/**").order(1)
32. // registry.addInterceptor(testInterceptor2).addPathPatterns("/**").excludePathPatterns("/userController/*").order(2);
33. }
34.
35.
36. }
The registration of interceptors is achieved by rewriting the addInterceptors method of the WebMvcConfigurer interface. When using the old version of WebMvcConfigurerAdapter, it is found that it has been eliminated and is not recommended.
3. Demonstration effect
Call the test interface to check the effect.
With token:
Without token:
In the preHandle method, it returns false if it directly determines that it fails, and no longer enters the controller and the other two methods.
3. Add three interceptors
Add three interceptors to test the sequential execution of multiple interceptors when they exist.
As in Section 2, add two more interceptors and register them in the interceptor register.
2.
3. import org.springframework.lang.Nullable;
4. import org.springframework.stereotype.Component;
5. import org.springframework.web.servlet.HandlerInterceptor;
6. import org.springframework.web.servlet.ModelAndView;
7.
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10.
11. /**
12. * @Classname TestIntercepter
13. * @Description TODO
14. * @Date 2022/4/12 9:03
15. * @Created by zrc
16. */
17. // Customize the interceptor by implementing the HandlerInterceptor interface and overriding its three methods. His three methods are the ones modified by the default keyword to have a default implementation.
18. @Component
19. public class TestInterceptor2 implements HandlerInterceptor {
20.
21. @Override
22. // Perform the operation before the request is sent to the controller controller, if it returns true it will enter the controller, if it returns false it will not enter the controller
23. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
24. System.out.println("Custom Interceptor 2 ----- start intercepting");;
25. return true; }
26. }
27.
28. @Override
29. // Used to perform the operation before the response is sent to the client, that is, the controller is executed after the return of data to execute.
30. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
31. System.out.println("Custom Interceptor 2 ----- Controller executed, returning data");;
32. }
33.
34. @Override
35. //Execute the operation after completing the request and response
36. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
37. System.out.println("Custom Interceptor 2 ----- response end");;
38. }
39.
40. }
2.
3. import org.springframework.lang.Nullable;
4. import org.springframework.stereotype.Component;
5. import org.springframework.web.servlet.HandlerInterceptor;
6. import org.springframework.web.servlet.ModelAndView;
7.
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10.
11. /**
12. * @Classname TestIntercepter
13. * @Description TODO
14. * @Date 2022/4/12 9:03
15. * @Created by zrc
16. */
17. // Customize the interceptor by implementing the HandlerInterceptor interface and overriding its three methods. His three methods are the ones modified by the default keyword to have a default implementation.
18. @Component
19. public class TestInterceptor3 implements HandlerInterceptor {
20.
21. @Override
22. // Perform the operation before sending the request to the controller controller, if it returns true it will go to the controller, if it returns false it will not go to the controller anymore
23. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
24. System.out.println("Custom Interceptor 3 ----- start intercepting");;
25. return true; }
26. }
27.
28. @Override
29. // Used to perform the operation before the response is sent to the client, that is, the controller is executed after the return of data to execute.
30. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
31. System.out.println("Custom Interceptor 3 ----- controller execution is complete, return data");;
32. }
33.
34. @Override
35. //Execute the operation after completing the request and response
36. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
37. System.out.println("Custom Interceptor 3 ----- response end");;
38. }
39.
40. }
Then register to the registrar.
2.
3. import org.springframework.context.annotation.Configuration;
4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
6.
7. import javax.annotation.Resource;
8.
9. /**
10. * @Classname TestIntercepterConfig
11. * @Description TODO
12. * @Date 2022/4/12 9:02
13. * @Created by zrc
14. */
15. // Older versions do this by inheriting the WebMvcConfigurerAdapter class, newer versions do it by implementing the WebMvcConfigurer interface.
16. @Configuration
17. public class TestInterceptorConfig implements WebMvcConfigurer {
18.
19. // Introduce a custom interceptor object
20. @Resource
21. private TestIntercepter testIntercepter;
22.
23. //Introduce custom interceptor object
24. @Resource
25. private TestIntercepter2 testIntercepter2;
26.
27. //Introduce custom interceptor object
28. @Resource
29. private TestIntercepter3 testIntercepter3;
30.
31. @Override
32. // Override addInterceptors method to register interceptors
33. public void addInterceptors(InterceptorRegistry registry){
34. // addInterceptor method to the interceptor registry to add interceptors, addPathPatterns method to add intercept path matching rules ("/**" is to intercept all), excludePathPatterns method is to set up a whitelist, which paths to release
35. // For the order of order.
36. // The interceptor's preHandle method executes in order. 37. // The postHandle and postHandle methods execute in order.
37. // The postHandle and afterCompletion methods are executed in reverse order. 38.
38. registry.addInterceptor(testInterceptor).addPathPatterns("/**").excludePathPatterns("/userController/*").order(1);
39. registry.addInterceptor(testInterceptor2).addPathPatterns("/**").excludePathPatterns("/userController/*").order(2);
40. registry.addInterceptor(testInterceptor3).addPathPatterns("/**").excludePathPatterns("/userController/*").order(3);
41. }
42.
43. }
Regarding the order of the order: the preHandle method of the interceptor is executed in order from small to large according to the size of the order, and the postHandle and afterCompletion methods are executed in reverse order from small to large according to the size of the order.
The demonstration results are as follows:
4. Compare interceptors and filters
In this section, learn the difference between the two through demo.
1. The interceptor is in spring and is managed by spring. It can be introduced into other beans managed by spring and used directly, but the filter cannot, as follows:
Add a new service managed by spring for testing
Retrofit Interceptor 1.
2. // before the request is sent to the controller controller to perform the operation, if the return of true on the controller, if the return of false on the controller is not entered
3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
4. // Compared to filters, interceptors can use reflection within methods to get information on the target interface, such as controller and method information. But you can't get the parameter list of the incoming parameter, you need aop faceted programming to do that.
5. // HandlerMethod handlerMethod = (HandlerMethod)handler;
6. // System.out.println(Arrays.toString(handlerMethod.getMethodParameters()));; } }
7. String token = request.getHeader("token"); 8. if(null!==0); if(null!
8. if(null!=token){
9. if(!token.equals(testServlet.test1())){
10. System.out.println("token is incorrect!") ;
11. return false;
12. }else {
13. System.out.println("Custom Interceptor 1----- started intercepting, before entering the controller, the interceptor intercepted the request and intercepted the token value as: "+token); ;return false
14. return true;
15. }
16. }else {
17. return false; }else {
18. }
19. }
Simulate a judgment to determine whether the token is correct or not, and it is found to be no problem when running.
If you perform this operation in the filter, as follows:
2. // The parameters request and response are the request and response objects passed from the Web server or the previous Filter in the Filter chain;
3. // the parameter chain represents the object of the current Filter chain.
4. //Only in the current Filter object within the doFilter () method need to call the FilterChain object of the doFilter () method in order to deliver the request to the Filter chain of the next Filter or target program processing
5. @Override
6. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { IOException, ServletException { IOException, ServletException { IOException, ServletException { IOException, ServletException ServletException {
7. HttpServletRequest req = (HttpServletRequest) servletRequest; // Here we are using a servletRequest to get a new servlet request.
8. // Here the token is transformed into an HttpServletRequest in order to use the getHeader method.
9. System.out.println("token: "+req.getHeader("token"));
10. System.out.println(servletRequest.getParameter("id"));
11. String token = req.getHeader("token");
12. //Then determine if the token is correct.
13. if(null==token){
14. throw new RuntimeException("token is null");
15. }
16. else{
17. if(!testServlet.test1().equals(token)){
18. throw new RuntimeException("token is incorrect!") ;
19. }
20. }
21. // Call the doFilter method and return the servletResponse normally.
22. filterChain.doFilter(servletRequest, servletResponse); }
23. }
operation result:
testServlet will report a null pointer. There are many opinions on the Internet. Some say that the loading time of the filter is earlier than that of the spring container. As a result, the bean object is still empty after loading the filter. Some say that it is because the filter belongs under javax.servlet. , not managed by the spring container. Filters also have methods to introduce spring bean objects for use, which will not be expanded here.
2. The interceptor is implemented by spring based on the reflection mechanism, and the filter is implemented based on servlet callbacks.
3. The interceptor can obtain the information of the methods on the controller layer through the input parameter handler of the preHandle method, except for the parameter list; while the filter can only obtain the request path, but cannot obtain the information of the methods on the controller layer.
Transform the preHandle method of interceptor 1
Test Results:
The filter cannot be obtained in this way.
That’s it for now.