这里主要介绍两种解决跨域请求的方法
一、注解方式
推荐这种方法,简单快捷,但Spring版本需要4.2以上,只需在spring-context.xml文件中添加如下配置即可,然后初始化时扫描这个文件
<!-- 解决跨域请求问题,spring版本需4.2以上 --> <mvc:cors> <mvc:mapping path="/**/**" allowed-origins="*" allowed-methods="POST, GET, OPTIONS, DELETE, PUT" allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" allow-credentials="true" /> </mvc:cors>
<servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:config/spring-*.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
二、拦截器方式
这种方法需要实现 Filter的doFilter方法,如下,即在web.xml文件中添加过滤器的配置,其中“ssm.util.filter.CORSFilter”是CORSFilter的引用位置
public class CORSFilter implements Filter { @Override public void init(FilterConfig var1) throws ServletException {} @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; response.addHeader("Access-Control-Allow-Origin", "*"); filterChain.doFilter(servletRequest, servletResponse); } public void destroy() {} }
<!--解决跨域访问--> <filter> <filter-name>CORSFilter</filter-name> <filter-class>ssm.util.filter.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>