拦截器的作用
将多个Cotroller中共有的代码放在拦截器中执行,减少Controller中的代码冗余,最常用的登录拦截、或是权限校验、或是防重复提交。
拦截器的特点
1)请求到达经过拦截器,响应回来经过拦截器
2)拦截器中断用户的请求轨迹
3)拦截器只能拦截控制器相关请求路径
springboot中拦截器开发步骤
1.自定义一个拦截器MyInterceptor实现HandlerInterceptor接口,不要忘记加上@Component注解创建组件
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//取出登陆标志位
Object user = request.getSession().getAttribute("user");
if(user == null){
//如果没有登陆 就重定向到登录页面 /shopcar是配置文件中设置的context-path
response.sendRedirect("/shopcar/view/LoginView.jsp");
return false;
}else{
//登录过了就放行
return true;
}
}
@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 {
}
}
这其中有三个方法:
- preHandle:在业务处理器处理请求之前被调用。预处理,可以进行编码、安全控制、权限校验等处理;
- postHandle:在业务处理器处理请求执行完成后,生成视图之前执行。后处理(调用了Service并返回ModelAndView,但未进行页面渲染),有机会修改ModelAndView (这个博主就基本不怎么用了);
- afterCompletion:在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。返回处理(已经渲染了页面);
2.新建InterceptorConfig继承WebMvcConfigurerAdapter类,覆盖其中的
addInterceptors方法,同样不要忘了加@Component注解
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Bean
public HandlerInterceptor getMyInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptor = registry.addInterceptor(getMyInterceptor());
// 拦截所有、排除
interceptor.addPathPatterns("/**")
.excludePathPatterns("/user/login");
}
}
这样一个拦截器的强制登录就实现了。