首先写一个自定义拦截器
实现这个接口 HandlerInterceptor
这里我们需要实现HandlerInterceptor这个接口,这个接口包括三个方法,preHandle是请求执行前执行的,postHandler是请求结束执行的,但只有preHandle方法返回true的时候才会执行,afterCompletion是视图渲染完成后才执行,同样需要preHandle返回true,该方法通常用于清理资源等工作。
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器运行preHandle .....");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle .....");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion .....");
}
}
配置添加拦截器
继承WebMvcConfigurationSupport
addInterceptor
添加自定义拦截器类
addPathPatterns
添加拦截路径
excludePathPatterns
排除指定路径
/**
* 添加拦截器
*/
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
//把自定义拦截器注入到spring容器里 这样就可以使用 @Autowired 注入Service层了
@Bean
public CheckTokenInterceptor checkTokenInterceptor(){
return new CheckTokenInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加检查token是否有效的拦截器
registry.addInterceptor(checkTokenInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/xx");
super.addInterceptors(registry);
}
}
网友评论