跨域资源共享

什么是跨域问题

参考:

  1. http://www.ruanyifeng.com/blog/2016/04/cors.html
  2. https://segmentfault.com/a/1190000015597029
Java服务端跨域问题的解决

上面已经介绍了什么是跨域问题,那么作为Java开发者,如果遇到了跨域问题,改怎么解决呢?
1、定义过滤器

public class CrossFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        //允许跨域请求
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie,Stype,Authorization,AppName,shopCode,userId");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,HEAD,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");

        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            return;
        }

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

2、web.xml中添加过滤器配置

<filter>
	<filter-name>crossDomainfilter-name>
	<filter-class>com.souche.scashier.web.filter.CrossFilterfilter-class>
filter>

<filter-mapping>
	<filter-name>crossDomainfilter-name>
	<url-pattern>/*url-pattern>
filter-mapping>

你可能感兴趣的:(Web)