SpringBoot|MVC|SpringCloud

Java设置接口跨域

         现在我们很多项目都是基于Java的REST结构风格前后端分离,在前端访问后端的时候就存在跨域,这个时候后端接口不处理就会存在访问不了。上代码!

 

  1、创建一个Filter 在web.xml中配置

<filter>
        <filter-name>xssAndSqlFilter</filter-name>
        <filter-class>com.tzdr.btc.user.filter.XssAndSqlFilter</filter-class>
        <!--过滤掉 静态资源文件 指定字符串  多个值用英文逗号隔开-->
        <init-param>
            <param-name>excludedPages</param-name>
            <param-value>/tesra/</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>xssAndSqlFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

  2、在Filter的doFiler方法中添加设置

@Override  
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
        boolean isExcludedPage = Boolean.TRUE;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest request1 = (HttpServletRequest) request;
        //*表示允许所有域名跨域
        httpResponse.setHeader("Access-Control-Allow-Origin", request1.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "0");
        httpResponse.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,Access-Control-Allow-Headers");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");//这个是设置运行携带cookie
        httpResponse.setHeader("XDomainRequestAllowed","1");
        //判断是否在过滤url之外
        for (String page : excludedPageArray) {
            if(((HttpServletRequest) request).getServletPath().contains(page)){
                isExcludedPage = Boolean.FALSE;
                break;
            }
        }
        //在过滤url之外
        if (isExcludedPage) {
            XssAndSqlHttpServletRequestWrapper xssRequest = new XssAndSqlHttpServletRequestWrapper((HttpServletRequest) request);
            chain.doFilter(xssRequest, response);
        }
        else{
            chain.doFilter(request, response);
        }
    }

 

这样完成以后 再访问接口就能成功访问了。

QQ群号:216868740

 

posted @ 2018-11-09 14:24  小三毛  阅读(9825)  评论(0编辑  收藏  举报
SpringBoot|MVC|SpringCloud