Java跨域解决

场景:2个不同语言的后端开发App,项目分别在两台服务器上,一台服务器上的H5网页中有需求需要请求另一台服务器的接口拿数据,造成跨域问题。

解决:

1.定义一个类,实现一个Filter接口(导包导servlet的包)

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleCORSFilter implements Filter {
    private boolean isCross = false;

    @Override
    public void destroy() {
        isCross = false;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (isCross) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            System.out.println("拦截请求: " + httpServletRequest.getServletPath());
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "0");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("XDomainRequestAllowed", "1");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println(isCrossStr);
    }
}

2.在web.xml中加上跨域的配置请求

    
    
        SimpleCORSFilter
        class>com.aone.app.filter.SimpleCORSFilterclass>
        
            IsCross
            true
        
    
    
        SimpleCORSFilter
        /*
    

3.在Springmvc.xml中配置跨域请求

     
     
         
                    allowed-origins="*"  
                    allowed-methods="POST, GET, OPTIONS, DELETE, PUT"  
                    allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"  
                    allow-credentials="true" />  
     

 4.maven依赖

    
    
      com.thetransactioncompany
      cors-filter
      2.5
    

 

来源:https://blog.csdn.net/qq_43491717/article/details/84134832

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