public class CrossInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.addHeader("Access-Control-Allow-Origin","*"); response.addHeader("Access-Control-Allow-Methods","*"); response.addHeader("Access-Control-Max-Age","100"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Allow-Credentials","false"); return super.preHandle(request, response, handler); } }
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**/*"/> <bean class="cn.***.filter.CrossInterceptor" /> </mvc:interceptor> </mvc:interceptors>
public class CrossFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { // CORS "pre-flight" request response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1800");//30 min } filterChain.doFilter(request, response); } }
<filter> <filter-name>cors</filter-name> <filter-class>cn.***.filter.CrossFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
升級spring版本的後,上述跨域並不支持全部瀏覽器。經測試,Safari正常,chrome異常。從新翻了一下最新的文檔後,獲得最新的跨域配置以下:angularjs
<mvc:cors> <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET,POST,OPTIONS"/> </mvc:cors>
相比3.x系列,簡單了不少。web