JAVA 与 AJAX 跨域问题解决方法

最近写项目遇到了跨域问题,浏览器报下面这样的错误
这里写图片描述

网上找了一堆解决方法 对自己都没用. 无奈干脆自己写了一个过滤器 写个类 继承 Filter

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
          HttpServletResponse res = (HttpServletResponse) servletResponse;
            HttpServletRequest request=(HttpServletRequest)servletRequest;
        res.setContentType("textml;charset=UTF-8");
        res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "0");
        res.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");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("XDomainRequestAllowed","1");
        filterChain.doFilter(servletRequest,servletResponse);

    }

不要管每一行什么意思 加上有用就完事了

在web.xml 里记得 添加上 初始化过滤器 不然写的没用
filter-class 写你类的全限定类名

<filter>
    <filter-name>loginFilterfilter-name>
    <filter-class>*.FilterJavafilter-class>
  filter>
  <filter-mapping>
    <filter-name>loginFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

同样的 前台AJAX 请求里面写上这句话

xhrFields: {
           withCredentials: true
       },
       crossDomain: true,

你可能感兴趣的:(java)