package com.runmin.bajie.intercepter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class AccessInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credential", "true"); response.setHeader("P3P", "CP=CAO PSA OUR"); if(request.getHeader("Access-Control-Request-Method")!=null&&"OPTIONS".equals(request.getMethod())) { response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept"); response.addHeader("Access-Control-Max-age", "120"); } return true; } }
<!-- 5.跨域拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/*/**"/> <bean class="com.runmin.bajie.intercepter.AccessInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
在MVC配置文件中配置如上即可。