java 跨域解决(OPTIONS)

一般跨域解决只需要在tomcat  conf下web.xml 里面设置


CorsFilter
org.apache.catalina.filters.CorsFilter

cors.allowed.origins
*


cors.allowed.methods
GET,POST,HEAD,OPTIONS,PUT


cors.allowed.headers
*


cors.exposed.headers
Access-Control-Allow-Origin,Access-Control-Allow-Credentials


cors.support.credentials
true



CorsFilter
/*

但遇到一些请求的  跨域  比如常见的OPTIONS   

请求  403  跨域  问题

写一个Filter,在doFilter里面加:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
    
        
        // 指定允许其他域名访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        // 响应类型
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");
        // 响应头设置
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");
        if ("OPTIONS".equals(req.getMethod())){
            resp.setStatus(HttpStatus.SC_NO_CONTENT);
        }
        chain.doFilter(request, response);
    }

 

即可解决   跨域问题  

 

 

 

你可能感兴趣的:(java 跨域解决(OPTIONS))