服务器端设置跨域请求

web.xml

<filter>
  <filter-name>CrossOrigin</filter-name>
  <filter-class>com.xx.filter.CrossOriginFilter</filter-class>
  <init-param>
    <param-name>AccessControlAllowOrigin</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>AccessControlAllowMethods</param-name>
    <param-value>POST, GET, DELETE, PUT</param-value>
  </init-param>
  <init-param>
    <param-name>AccessControlMaxAge</param-name>
    <param-value>3628800</param-value>
  </init-param>
  <init-param>
    <param-name>AccessControlAllowHeaders</param-name>
    <param-value>x-requested-with</param-value>
  </init-param>
</filter>

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

CrossOriginFilter

package com.xx.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2017/5/3 0003.
 */
public class CrossOriginFilter implements Filter {

    private FilterConfig config = null;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void destroy() {
        this.config = null;
    }

    /**
     *
     * @comment 跨域的设置
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 表明它允许"http://xxx"发起跨域请求
        httpResponse.setHeader("Access-Control-Allow-Origin",
                config.getInitParameter("AccessControlAllowOrigin"));
        // 表明在xxx秒内,不需要再发送预检验请求,可以缓存该结果
        httpResponse.setHeader("Access-Control-Allow-Methods",
                config.getInitParameter("AccessControlAllowMethods"));
        // 表明它允许xxx的外域请求
        httpResponse.setHeader("Access-Control-Max-Age",
                config.getInitParameter("AccessControlMaxAge"));
        // 表明它允许跨域请求包含xxx头
        httpResponse.setHeader("Access-Control-Allow-Headers",
                config.getInitParameter("AccessControlAllowHeaders"));
        chain.doFilter(request, response);
    }

}

关于跨域问题的解决方案

参考链接:http://blog.csdn.net/qq_31617637/article/details/72955239

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值