ajax跨域访问解决方案

第一步:

创建 SimpleCORSFilter.java 文件

package net.csdn.web.controller;

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.HttpServletResponse;

/**
 * Java项目跨域问题解决方案
 * 
 * @date: 2017年08月31日  上午00:00:00
 * @author: LiuMing
 */
public class SimpleCORSFilter implements Filter {

    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.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");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {

    }

    public void destroy() {

    }
}

第二步:

找到项目中的 web.xml 文件并配置如下代码


<filter>
    <filter-name>corsfilter-name>
    <filter-class>net.csdn.web.controller.SimpleCORSFilterfilter-class>
filter>
<filter-mapping>
    <filter-name>corsfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

你可能感兴趣的:(解决方案)