Home  >  Article  >  Java  >  Example analysis of Java implementing CORS cross-domain requests

Example analysis of Java implementing CORS cross-domain requests

黄舟
黄舟Original
2017-09-23 09:44:221502browse

This article mainly introduces the implementation method of CORS cross-domain request in Java. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

Problem

When developing projects using the front-end and back-end separation mode, you often encounter such a problem--unable to obtain services across domains End data

This is caused by the browser's same-origin policy and is for security. Today, when the front-end and back-end separation development model is very popular, front-end and back-end projects are often developed in different environments. At this time, there will be a need to request data across domains. The current solutions mainly include the following:

JSONP, iframe, proxy mode, CORS, etc.
I won’t talk about the previous methods here, there is a lot of information on the Internet. Here I will mainly share the CORS solution. CORS stands for "cross-domain resource sharing". It allows the browser to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the limitation that AJAX can only be used from the same source.

The process of using CORS cross-domain is the same as the ordinary ajax process, except that the browser will automatically handle some things for us when it finds that this is a cross-domain request, so as long as the server provides support, There is no need to do anything extra on the front end.

Implementation

The general idea of ​​​​implementation is this. First, use a filter to obtain the information of the request object request, such as the Origin field (indicating which source the request comes from, including the protocol , domain name, port), determine whether the request is legal through the pre-configured parameters, and then set the header information of the response object to implement cross-domain resource requests. Before introducing the implementation method, let's first understand the response header information that will be used.

Response header

Access-Control-Allow-Methods
Used to list the HTTP methods allowed by the browser's CORS request, such as: GET, POST , PUT, DELETE, OPTIONS

Access-Control-Allow-Credentials
Indicates whether to support cross-domain cookies

Access-Control-Allow-Headers
Comma-separated string, Indicates all header information fields supported by the server, such as Content-Type and custom fields

Access-Control-Expose-Headers
The opposite of "Access-Control-Allow-Headers", indicating that it is not supported Header information field

Access-Control-Allow-Origin
Allows cross-domain request source information, including protocol, domain name, and port. * means all request sources are allowed, and only one request source can be set

The following is an introduction to how the Java background implements this method.

Code

Since I have been using spring-boot recently, I will implement it based on spring-boot.

First create a CorsFilter filter. The code is as follows:


...
@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() {

  }
}

It’s done. Now the front-end can obtain the background data across domains, which is easier than other methods. If it is too much, the code will not be explained. It is simple and easy to understand. It is the same when using other back-end development methods. The ultimate goal is to judge the request and set the response header. The front-end does not have to do anything.

The above is the detailed content of Example analysis of Java implementing CORS cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn