SpringBoot 多個版本配置簡單的攔截器
阿新 • • 發佈:2019-01-10
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 {
}
}