使用:java
實現HandlerInterceptor接口api
- 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接口tomcat
- preHandle方法無返回值 - postHandle - afterCompletion
使用場景app
使用:實現Filter接口cors
具體代碼框架
/** * 經過過濾器實現跨域處理 */ @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() {} }