This article will talk about interceptors. It is convenient to register interceptors in springboot. There are about two steps:
1. Implement HandlerInterceptor interface to create interceptor
2. Implementation of WebMvcConfigurer interface configuration interceptor
Let's use a simple example to roughly show the following specific use:
Scenario: two pages, the login page can be accessed at will, but the home page can only be accessed by xiongda user after entering the correct password
The first step is to create an interceptor
public class MyInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("==========jin ru pre handle ===="); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username +","+password); if("xiongda".equals(username) && "123456".equals(password)) { return true; }else { return false; } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("================= jin ru after ==============="); } }
Second, configure the interceptor
@Configuration public class WebMvcConfig implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/static/login.html"); } }
Next, we will explain according to the specific results:
The above two figures are to access the login page. The login page is configured with the exclusion path in the interceptor configuration. You can see that even if it is released, it will enter the prehandle, but no operation will be performed.
When entering the home page, the judgment will be made in the prehandle. Only when it is true will the subsequent afterCompletion method be executed.
Note:
1. The execution order of methods in the interceptor is prehandle - > controller - > posthandle - > aftercompletion.
Only when preHandle returns true will the following methods be executed