_
拦截器相对与过滤器Filter 而言,拦截器是spring中的概念。过滤器是servlet中的概念。在spring中肯定是优先使用拦截器Interceptor的。
public class My1Interceptor extends HandlerInterceptorAdapter {
/**
* 请求在处理之前时,调用这个方法
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.err.println("==>preHandle........................");
// 因为是模拟,所以token就加在url后面
String token = request.getParameter("token");
if(token !=null && token.equals("true")) {
System.err.println("token is valid,procedue.");
return super.preHandle(request, response, handler);
}else {
System.err.println("token is invalid,redirect to login page.");
String url = request.getContextPath() + "/login";
System.err.println(url);
response.sendRedirect(url);
return false;
}
}
/**
* 请求在处理之后,调用这个方法
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.err.println("==>postHandle........................");
super.postHandle(request, response, handler, modelAndView);
}
/**
* 请求在完成postHandle处理之后,调用这个方法
* 如果请求在preHandle时被return false,这个方法不会执行
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.err.println("==>afterCompletion........................");
super.afterCompletion(request, response, handler, ex);
}
}
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new My1Interceptor()).addPathPatterns("/do*");
// 这里还可以注册别的拦截器
// 这里还可以注册别的拦截器
// 这里还可以注册别的拦截器
super.addInterceptors(registry);
}
}
https://www.cnblogs.com/panxuejun/p/7715917.html