LeeEmmmm 2019-07-01
使用:
实现HandlerInterceptor接口
- preHandle:返回值:boolean表示是否需要将当前的请求拦截下来。方法中Object对象标识的是被拦截的请求的目标对象 - postHandle:在DispatcherServlet进行视图返回渲染之前被调用 - afterCompletion:在DispatcherServlet渲染了对应的视图之后执行,这个方法的主要作用是用于进行资源清理的工作
具体代码
/** * 注册拦截器 */ @SpringBootConfiguration public class WebConfig implements WebMvcConfigurer { @Autowired DataInterceptor dataInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //拦截路径,表示此路径下的所有地址都会先执行此拦截器,通过之后才能访问Controller String[] addPathPatterns = { "/api/**" }; registry.addInterceptor(dataInterceptor).addPathPatterns(addPathPatterns); } } /** * 新建拦截器 */ @Component(value = "dataInterceptor") public class DataInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Systemt.out.println("新建拦截器"); return true; } }
实现WebRequestInterceptor接口
- preHandle方法无返回值 - postHandle - afterCompletion
使用场景
使用:实现Filter接口
具体代码
/** * 通过过滤器实现跨域处理 */ @Order(1) @Component @WebFilter(urlPatterns = { "/api/*"}, filterName = "corsFilter") public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "authorization, authorizationToken, appCode, x-requested-with, Content-Type, Access-Token"); response.setHeader("Access-Control-Expose-Headers", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() {} }