Springmvc ajax cross-origin request processing and springmvcajax cross-Origin
The last time I wrote a website to separate the front and back ends of the website, I finally squatted on the ajax cross-domain interface. I found a method on the Internet to record it.
Write a class to inherit HandlerInterceptorAdapter
Package com. util; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. web. servlet. handler. handlerInterceptorAdapter; public class CommonInterceptor extends HandlerInterceptorAdapter {public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {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", "Origin, X-Requested-With, Content-Type, Accept"); response. setHeader ("Access-Control-Allow-Credentials", "true"); // whether to Allow the browser to carry user identity information (cookie) return true ;}}
Configure the path in xml
<Mvc: interceptors> <! -- Filter all requests and handle cross-origin requests --> <mvc: interceptor> <mvc: mapping path = "/**"/> <bean class = "com. util. commonInterceptor "/> </mvc: interceptor> </mvc: interceptors>
This is fine, but there is a blog saying that there is no problem with simple cross-origin. However, the post + json request fails, prompting that the cross-origin request fails. So let's record his solution.
Create a class to inherit OncePerRequestFilter
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); }}
Set it in web. xml
<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>
The above method is spring3.0. If it is 4.0, you can use the following method (no test)
Xml configuration
<mvc:cors> <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET,POST,OPTIONS"/> </mvc:cors>
Part of the blog http://www.cnblogs.com/asfeixue/p/4363372.html that references the snow of flying