拦截器作用位置
拦截器的作用与过滤器大抵相同,过滤器是作用于客户端与前端控制器之间,拦截器则作用域前端控制器与处理器映射器,适配器之间
拦截器
1.建拦截器包和类
放入容器内:@Component
实现接口:implements HandlerInterceptor
@Component
//到了拦截器的请求,都必须全部登录才能访问
public class LoginAuthInterceptor implements HandlerInterceptor {
//在controller方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object author = request.getSession().getAttribute("author");
if (author == null) {
//2.1没登录,那就去登陆页面,过一次controller
response.sendRedirect("/author/loginPage");
return false;
} else {
//2.2已经登录的直接放行
return true;
} }
//在controller方法执行之后
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
//请求完成视图解析之后
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
2.建配置类包和类
springMvc的配置类
配置类:@Configuration
springMvc配置类: implements WebMvcConfigurer
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginAuthInterceptor loginAuthInterceptor;
//拦截器的配置类:配置这个拦截器在什么时候工作
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置这个拦截器
registry.addInterceptor(loginAuthInterceptor)
//要拦截那些请求 (就是拦截的)
.addPathPatterns("/**")
//排除哪些请求 (就是放行的)
.excludePathPatterns("/author/loginPage","/author/login",
"/author/registerPage","/author/register",
"favicon.ico","/imgCode",
"/bootstrap/**","/js/**");
}
}