拦截器是在servlet执行之前执行的程序(这里就是controller代码执行之前),它主要是用于拦截用户请求并作相应的处理,比如说可以判断用户是否登录,做相关的日志记录,也可以做权限管理。
public class UserInterceptor implements HandlerInterceptor{
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
//编写业务拦截规则
//从sessin中获取用户的信息
blogger blogger = (com.yida.bean.blogger) request.getSession().getAttribute("blogger");
if (blogger==null) {
response.sendRedirect("/admin");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("controller 执行完了");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception { System.out.println("我获取到了一个返回的结果:"+response);
System.out.println("请求结束了");
}
}
@Configuration //定义此类为配置类,及相当于之前的xml文件
public class InterceptorConfig implements WebMvcConfigurer{
//添加我们的拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
String[] excludePathPatterns = {"/admin","/admin/login"};
WebMvcConfigurer.super.addInterceptors(registry);
//已经提供了拦截器注册类 放进来相当于定义了一个bean
registry.addInterceptor(new UserInterceptor()).addPathPatterns("/admin/**").excludePathPatterns(excludePathPatterns);
}
}