Java设置接口跨域

Posted 小三毛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于Java设置接口跨域的主要内容,如果未能解决你的问题,请参考以下文章

java 代码片段

跨域拦截Access-Control-Allow-Origin设置多个origin

java代码跨域通用方法

egg.js 跨域 设置cookie

Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段

cocos2d-js访问java程序跨域问题