当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现CORS跨域请求的实现方法

Java实现CORS跨域请求的实现方法

2019年07月19日  | 移动技术网IT编程  | 我要评论
问题 使用前后端分离模式开发项目时,往往会遇到这样一个问题 -- 无法跨域获取服务端数据 这是由于浏览器的同源策略导致的,目的是为了安全。在前后端分离开发模式备受青睐的

问题

使用前后端分离模式开发项目时,往往会遇到这样一个问题 -- 无法跨域获取服务端数据

这是由于浏览器的同源策略导致的,目的是为了安全。在前后端分离开发模式备受青睐的今天,前端和后台项目往往会在不同的环境下进行开发,这时就会出现跨域请求数据的需求,目前的解决方案主要有以下几种:

jsonp、iframe、代理模式、cors等等
前面几种方式在这里不讲,网上有很多资料。在这里我主要分享一下cors这种解决方式,cors即“跨域资源共享”,它允许浏览器向跨源服务器,发出xmlhttprequest请求,从而克服了ajax只能同源使用的限制。

使用 cors 跨域的时候和普通的 ajax 过程是一样的,只是浏览器在发现这是一个跨域请求的时候会自动帮我们处理一些事情,所以说只要服务端提供支持,前端是不需要做额外的事情的。

实现

实现的大概思路是这样的,首先使用过滤器获取请求对象request的信息,比如origin 字段(表示请求来自哪个源,包括协议、域名、端口),通过预先配置的参数判断请求是否合法,然后设置响应对象response的头信息,实现跨域资源请求。在介绍实现方式之前我们先来了解一下会用到的响应头信息。

响应头

access-control-allow-methods
用来列出浏览器的cors请求允许使用的http方法,如:get、post、put、delete、options

access-control-allow-credentials
表示是否支持跨域cookie

access-control-allow-headers
逗号分隔的字符串,表示服务器支持的所有头信息字段,如content-type以及自定义的字段

access-control-expose-headers
与“access-control-allow-headers”相反,表示不支持的头信息字段

access-control-allow-origin
允许跨域的请求源信息,包括协议、域名、端口,为*表示允许所有请求来源,并且只能设置一个请求源

下面介绍一下java后台如何实现这种方式。

代码

由于最近在使用spring-boot,所以接下来以spring-boot为基础来实现。

首先创建一个corsfilter过滤器,代码如下:

...
@webfilter(filtername = "corsfilter", urlpatterns = "/*",
    initparams = {@webinitparam(name = "alloworigin", value = "*"),
        @webinitparam(name = "allowmethods", value = "get,post,put,delete,options"),
        @webinitparam(name = "allowcredentials", value = "true"),
        @webinitparam(name = "allowheaders", value = "content-type,x-token")})
public class corsfilter implements filter {

  private string alloworigin;
  private string allowmethods;
  private string allowcredentials;
  private string allowheaders;
  private string exposeheaders;

  @override
  public void init(filterconfig filterconfig) throws servletexception {
    alloworigin = filterconfig.getinitparameter("alloworigin");
    allowmethods = filterconfig.getinitparameter("allowmethods");
    allowcredentials = filterconfig.getinitparameter("allowcredentials");
    allowheaders = filterconfig.getinitparameter("allowheaders");
    exposeheaders = filterconfig.getinitparameter("exposeheaders");
  }

  @override
  public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception {
    httpservletrequest request = (httpservletrequest) servletrequest;
    httpservletresponse response = (httpservletresponse) servletresponse;
    if (!stringutils.isempty(alloworigin)) {
      if(alloworigin.equals("*")){
        response.setheader("access-control-allow-origin", alloworigin);
      }else{
        list<string> alloworiginlist = arrays.aslist(alloworigin.split(","));
        if (alloworiginlist != null && alloworiginlist.size() > 0) {
          string currentorigin = request.getheader("origin");
          if (alloworiginlist.contains(currentorigin)) {
            response.setheader("access-control-allow-origin", currentorigin);
          }
        }
      }
    }
    if (!stringutils.isempty(allowmethods)) {
      response.setheader("access-control-allow-methods", allowmethods);
    }
    if (!stringutils.isempty(allowcredentials)) {
      response.setheader("access-control-allow-credentials", allowcredentials);
    }
    if (!stringutils.isempty(allowheaders)) {
      response.setheader("access-control-allow-headers", allowheaders);
    }
    if (!stringutils.isempty(exposeheaders)) {
      response.setheader("access-control-expose-headers", exposeheaders);
    }
    filterchain.dofilter(servletrequest, servletresponse);
  }

  @override
  public void destroy() {

  }
}

大功告成,现在前端就可以跨域获取后台的数据了,比其它方式容易得多,代码就不解释了,简单易懂,使用其它后台开发方式也一样,最终目的就是判断请求,设置响应头,前端什么事都不用做。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网