Home  >  Article  >  Java  >  How to configure Access-Control-Allow-Origin in Java to allow access from multiple domain names.

How to configure Access-Control-Allow-Origin in Java to allow access from multiple domain names.

王林
王林forward
2023-05-09 08:58:072778browse

For projects with front-end and back-end separation, it is inevitable to encounter cross-domain problems. There are many things that need to be paid attention to when setting up cross-domain problems. For example, this time we will set Access-Control-Allow-Origin to allow multiple Domain name request.

(1) The simplest way to set up to allow access to multiple domain names is to use wildcards, but this method allows all domain names to be accessed, which is not safe, and in this way the browser cannot carry cookie information (carrying cookies Information can only use real domain names, as shown in the second method below). This method is only recommended for testing in development without cookie information. The code is as follows:

rep.setHeader("Access-Control-Allow-Origin", "*");

(2) Using array filtering

@Override
 public void doFilter(ServletRequest request, ServletResponse response,
       FilterChain chain) throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse rep = (HttpServletResponse) response;
  // 设置允许多个域名请求
  String[] allowDomains = {"http://www.toheart.xin","http://192.168.11.213:8080","http://localhost:8080"};
  Set allowOrigins = new HashSet(Arrays.asList(allowDomains));
  String originHeads = req.getHeader("Origin");
  if(allowOrigins.contains(originHeads)){
   //设置允许跨域的配置
   // 这里填写你允许进行跨域的主机ip(正式上线时可以动态配置具体允许的域名和IP)
   rep.setHeader("Access-Control-Allow-Origin", originHeads);
  }

The above is the detailed content of How to configure Access-Control-Allow-Origin in Java to allow access from multiple domain names.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete