前后端分离,java配置跨域请求问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/athur666/article/details/70739282

最近写的项目采用的是spring-mvc+mybatis 由于前后端分离开发,采用json进行数据传输,这样就必须解决跨域的问题了。

跨域的jar包:cors-filter.jar

       处理跨域的问题就是直接设置请求头,加上以下代码即可,这样设置就不限制任何人访问

response.setHeader("Access-Control-Allow-Origin","*");    此处*代表任何人都可以访问  或者填一个ip地址,则指定一个ip地址可以访问 
       response.addHeader("Access-Control-Allow-Headers",
               "origin, content-type, accept, authorization");
       response.addHeader("Access-Control-Allow-Credentials", "true");
       response.addHeader("Access-Control-Allow-Methods","GET, POST, PUT,DELETE, OPTIONS, HEAD");    
 

然后在web.xml中加入以下配置

<filter>  
    <filter-name>cors</filter-name>  
       <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>  
</filter>  
<filter-mapping>  
    <filter-name>cors</filter-name>  
    <url-pattern>/*</url-pattern>  
 </filter-mapping>


猜你喜欢

转载自blog.csdn.net/athur666/article/details/70739282