java 前后端分离,跨域问题及获取响应头信息

时间:2022-02-08 21:10:22

java 前后端分离,跨域问题及获取响应头信息


跨域问题解决方案 :

基础filter 实现doFilter方法
public class CORSFilter  implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }


    @Override
    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.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");//Access-Control-Allow-Headers配置允许前端提交的请求头信息
response.addHeader("Access-Control-Expose-Headers", "GID,SID");//Access-Control-Expose-Headers配置允许前端获取到的请求头信息
        chain.doFilter(req, res);
    }


    @Override
    public void destroy() {


    }
}
web.xml:
<!-- cors跨域 -->
<filter>  
        <filter-name>CORS</filter-name>  
        <filter-class>com.wld.common.CORSFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>CORS</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>




或者:


pom.xml:
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.6</version>
</dependency>




web.xml:
<!-- cors跨域 -->
<filter>  
        <filter-name>CORS</filter-name>  
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>  
        <init-param>  
            <param-name>cors.allowOrigin</param-name> 
            <param-value>*</param-value> 
        </init-param>  
        <init-param>  
            <param-name>cors.supportedMethods</param-name> 
            <!-- GET, POST, HEAD, PUT, DELETE -->
            <param-value>POST</param-value> 
        </init-param>  
        <init-param>  
            <param-name>cors.supportedHeaders</param-name> 
            <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified,SID,GID</param-value>
        </init-param>  
        <init-param>  
            <param-name>cors.exposedHeaders</param-name> 
            <param-value>Set-Cookie,SID,GID</param-value>
        </init-param>  
        <init-param>  
            <param-name>cors.supportsCredentials</param-name> 
            <param-value>true</param-value> 
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CORS</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>


参考资料:https://developer.mozilla.org/z-US/docs/Web/HTTP/CORS