springboot1.x 和 springboot2.x 配置拦截器区别就在于注册拦截器的方式不同,springboot1.x 配置方法是:
public class WebAppConfig extends WebMvcConfigurerAdapter {
springboot2.x 配置方法是:
public class LoginConfigurer implements WebMvcConfigurer {
下面详细的介绍使用方法。
一、springboot1.x 配置方法
1、注册拦截器
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器,添加拦截路径和排除拦截路径
registry.addInterceptor(new InterceptorConfig()).addPathPatterns("user/**").excludePathPatterns("admin/login");
}
}
2、实现 实现 HandlerInterceptor 接口
public class InterceptorConfig implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
二、springboot2.x 配置方法
一、注册拦截器
@Configuration
public class LoginConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加一个拦截器,连接以/authorize为前缀的url路径
registry.addInterceptor(new LoginURLInterceptor()).addPathPatterns("/pageController/authorize/**");
}
}
2、实现 HandlerInterceptor 接口
public class LoginURLInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("访问了/pageController/loginPage路径。");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
标签:Exception,拦截器,SpringBoot,Object,HttpServletResponse,版本,Override,public
From: https://www.cnblogs.com/mountainstudy/p/17603862.html