跨域CORS支持

2018-03-22  本文已影响0人  小正2

1、SpringMVC 4.2以上版本。

2、添加sping配置:

    <mvc:cors>
        <mvc:mapping path="/**" />
    </mvc:cors>

3、添加过滤器CORSFilter:

@Component

public class CORSFilter implements Filter{

     public void destroy() {}

     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)  

     throws IOException, ServletException {

         HttpServletResponse response = (HttpServletResponse) res; 

        response.setHeader("Access-Control-Allow-Origin", "*"); 

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 

        response.setHeader("Access-Control-Max-Age", "3600"); 

        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 

    chain.doFilter(req, res);

     }

     public void init(FilterConfig arg0) throws ServletException {}

}

4、web.xml中添加配置

<filter>

    <filter-name>cors</filter-name>

    <filter-class>com.account.admin.filter.CORSFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>cors</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

上一篇下一篇

猜你喜欢

热点阅读