Implement CORS requests in Java and cross-origin in Java

Source: Internet
Author: User

Implement CORS requests in Java and cross-origin in Java
Problem

When you use the frontend and backend separation mode to develop a project, you will often encounter this problem-you cannot obtain server data across domains.

This is caused by the same-source policy of the browser and is designed for security. Today, the development mode of separation from the front and back ends is favored. front-end and back-end projects are often developed in different environments, and cross-origin request data is required, currently, the following solutions are available:

JSONP, iframe, proxy mode, CORS, etc.

The previous methods are not mentioned here. There is a lot of information on the Internet. Here I will mainly share with you the CORS solution. CORS is "cross-origin Resource Sharing", which allows browsers to send XMLHttpRequest requests to cross-source servers, thus overcoming the restrictions that AJAX can only use the same origin.

CORS is the same as the normal ajax process, but the browser automatically handles some tasks when discovering that this is a cross-origin request.As long as the server provides support, the front-end does not need to do anything else..

Implementation

The general idea of implementation is as follows: first, use a filter to obtain the request information of the request object, such as the Origin field (indicating the source of the request, including the protocol, domain name, and port ), the pre-configured parameters are used to determine whether the request is valid, and then the response object response header information is set to implement cross-origin resource requests. Before introducing the implementation method, let's take a look at the response header information that will be used.

Response Header
  • Access-Control-Allow-Methods
    Used to list HTTP methods allowed by browser CORS requests, such as GET, POST, PUT, DELETE, and OPTIONS.

  • Access-Control-Allow-Credentials
    Indicates whether cross-origin cookies are supported.

  • Access-Control-Allow-Headers
    A comma-separated string that indicates all header information fields supported by the server, such as Content-Type and custom fields.

  • Access-Control-Expose-Headers
    Opposite to "Access-Control-Allow-Headers", the header information field is not supported.

  • Access-Control-Allow-Origin
    Allow cross-origin request source information, including Protocol, domain name, port*Allow all request sources andOnly one request source can be set

The following describes how to implement this method in the Java background.

Code

Since spring-boot is recently used, it is implemented based on spring-boot.

First, create a CorsFilter. 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() {    }}

As a result, the front-end can now obtain data from the background through cross-origin, which is much easier than other methods. The code is not explained and easy to understand. The same applies to other background development methods, the final goal is to determine the request and set the response header. The front-end does not need to do anything.

Java study and exchange QQ group: 589809992 chat prohibited, do not enter!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.