java,spring,tomcat,跨域设置详解编程语言

通过工具远程访问rest会出现

 已阻止跨源请求:同源策略禁止读取位于 
java,spring,tomcat,跨域设置详解编程语言http://XXXXX:1200/gyly/busData 的远程资源。(原因:CORS 请求失败)。 
修改方法
添加Filter

import java.io.IOException;   
   
import javax.servlet.FilterChain;   
import javax.servlet.ServletException;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
   
import org.springframework.web.filter.OncePerRequestFilter;   
   
public class CorsFilter extends OncePerRequestFilter {   
   
 @Override   
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)   
            throws ServletException, IOException {   
    response.addHeader("Access-Control-Allow-Origin", "*");   
    response.addHeader("Access-Control-Allow-Methods",   
            "GET, POST, PUT, DELETE, OPTIONS");   
    response.addHeader("Access-Control-Allow-Headers",   
            "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");   
        filterChain.doFilter(request, response);   
    }   
}  

修改web.xml

<filter>   
  <filter-name>CorsFilter</filter-name>   
  <filter-class>com.interfaceservice.filter.CorsFilter</filter-class>   
</filter>   
<filter-mapping>   
  <filter-name>CorsFilter</filter-name>   
  <url-pattern>/*</url-pattern>   
</filter-mapping>  

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/19456.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论