spring boot拦截器默认有
- HandlerInterceptorAdapter
- AbstractHandlerMapping
- UserRoleAuthorizationInterceptor
- LocaleChangeInterceptor
- ThemeChangeInterceptor
配置spring mvc的拦截器 WebMvcConfigurationSupport ( WebMvcConfigurerAdapter 已过时 )
1. 配置拦截器
package com.example.utils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class ConfigurerUtil extends WebMvcConfigurationSupport{
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserLogoutInterceptor()).addPathPatterns("/**").excludePathPatterns("/user_login.html","/login.html/verification",
"/user_login.html/back");
super.addInterceptors(registry);
}
}
registry.addInterceptor可以通过此方法添加拦截器, 可以是spring提供的或者自己添加的拦截路径,excludePathPatterns可以通过此方法添加不需要拦截的路径
拦截器可以添加多个,按顺序执行
2.实现自定义拦截器
package com.example.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class UserLogoutInterceptor implements HandlerInterceptor{
/***
* 在请求处理之前调用 (controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("被 user拦截器 拦截 --> 放行");
//return HandlerInterceptor.super.preHandle(request, response, handler);
return true;
}
/***
* 请求处理之后进行调用,但是在视图渲染之前(controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/***
* 再整个请求被调用之后, 也就是在DispatcherServlet 渲染了对应的视图之后执行。
* (只要是进行资源清理工作 缓存 垃圾回收)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}