Five ways to realize cross domain in SpringBoot

1, Why do cross domain problems occur

Due to the homology policy restriction of the browser. The same origin policy is a kind of agreement. It is the core and basic security function of the browser. If the same origin policy is missing, the normal functions of the browser may be affected. It can be said that the Web is built on the basis of homologous strategy, and the browser is only an implementation of homologous strategy.

The same origin policy prevents the javascript script of one domain from interacting with the content of another domain. The so-called homology (i.e. in the same domain) means that two pages have the same protocol, host and port number

2, What is cross domain

When any of the protocol, domain name and port of a request url is different from the current page url, it is cross domain


3, Non homologous restriction

[1] Unable to read cookies, LocalStorage and IndexedDB of non homologous web pages

[2] Unable to contact the DOM of non homologous web pages

[3] Unable to send AJAX request to non homologous address

4, How to implement cross domain request of CORS in java backend

For cross domain requests of CORS, there are mainly the following ways to choose from:

  1. Return to the new CorsFilter

  2. Override WebMvcConfigurer

  3. Use annotation @ CrossOrigin

  4. Manually set the response header (HttpServletResponse)

  5. Cross domain implementation of custom web filter


  • Corfilter / webmvconfigurator / @ crossorigin requires spring MVC version 4.2 or above to support, corresponding to springboot version 1.3 or above

  • The first two methods above belong to global CORS configuration, and the last two belong to local CORS configuration. If a local cross domain rule is used, it will override the global cross domain rule. Therefore, the @ CrossOrigin annotation can be used for finer grained cross domain resource control.

  • In fact, the ultimate goal of any scheme is to modify the response header and add the data required by the browser to the response header, so as to realize cross domain


1. Return to the new corsfilter (Global cross domain)

In any configuration class, return a new CorsFIlter Bean, and add the mapping path and specific CORS configuration path.

public class GlobalCorsConfig {
    public CorsFilter corsFilter() {
        //1. Add CORS configuration information
        CorsConfiguration config = new CorsConfiguration();
        //Which original release domains
        //Send cookies
        //Which request methods are released
        //Which original request header information is released
        //What header information is exposed
        //2. Add mapping path
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        //3. Return to the new CorsFilter
        return new CorsFilter(corsConfigurationSource);

2. Rewrite webmvcconfigurer (Global cross domain)

public class CorsConfig implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry) {
                //Send cookies
                //Which original domains are released
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})

3. Use annotations (local and cross domain)

Use the annotation @ CrossOrigin: on the controller (class) to indicate that all methods of this class allow cross domain.

@CrossOrigin(origins = "*")
public class HelloController {
    public String hello() {
        return "hello world";

Use annotation @ CrossOrigin:

    @CrossOrigin(origins = "*")
     //@CrossOrigin(value = " http://localhost:8081 ") / / specify the specific ip address and allow cross domain
    public String hello() {
        return "hello world";

4. manually set the response header (local cross domain)

Use the HttpServletResponse object to add a response header (access control allow Origin) to authorize the original domain. Here, the value of Origin can also be set to "*", indicating all release. recommend: Decomposition and summary of 150 common Java interview questions

public String index(HttpServletResponse response) {
    return "index";

5. Use custom filter to realize cross domain

First write a filter, which can be named mycorsfilter java

package com.yzgu.aop;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
    chain.doFilter(req, res);
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}

On the web Configure this filter in XML to make it effective

<!-- Cross domain access START-->
<!-- Cross domain access END  -->

Tags: Java http servlet filter

Posted by kjb on Sun, 17 Apr 2022 01:01:37 +0930