SoFunction
Updated on 2025-04-14

Springboot's cross-domain implementation method (with Demo)

Springboot handles cross-domain

1. Basic knowledge

Cross-domain refers to a web page under one domain trying to access resources under another domain

Due to the same-origin policy of the browser, JavaScript can only be requested in the same domain by default

Cross-domain usually involves the following concepts:

  • Origin: Including protocol, domain name and port number
    For example:80
  • Same-Origin Policy: Browser security policy that restricts how documents or scripts from one source can interact with resources from another source
  • CORS: Mechanisms that allow cross-domain requests
    The server informs the browser which sources are allowed to access by setting specific response headers

In Spring Boot, there are several ways to deal with cross-domain. Here are the main ways:

  1. Use @CrossOrigin annotation: This method is relatively simple and suitable for the controller layer
  2. Configure global cross-domain settings: This method is suitable for global configuration and can be set in the Web configuration class
  3. Customize CorsConfiguration: Suitable for more complex cross-domain configuration requirements, can be customized in the configuration class

The following is a demo example

2. @CrossOrigin

You can add @CrossOrigin annotation to the controller class or method

The annotated parameters can configure the allowed origins, the allowed request methods, the allowed request headers, whether to allow credentials, etc.

import ;
import ;
import ;
import ;

@RestController
@RequestMapping("/api")
public class MyController {

    @CrossOrigin(origins = "")
    @GetMapping("/data")
    public String getData() {
        return "Data from server";
    }
}

If you do not use the @CrossOrigin annotation, the browser blocks cross-domain requests, because the default same-origin policy does not allow requests between different sources.

3. Global cross-domain settings

Configurer to globally set cross-domain

import ;
import ;
import ;
import ;

/**
  * Configuration class, used to set CORS (cross-domain resource sharing) configuration globally
  */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
      * Configure mapping rules for cross-domain requests
      *
      * @param registry registry for registering CORS configuration
      */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // Add cross-domain mapping rules        ("/**")  // Allow cross-domain requests for all paths                .allowedOrigins("")  // Allow cross-domain requests from                .allowedMethods("GET", "POST", "PUT", "DELETE")  // Allowed request method                .allowedHeaders("*")  // All request headers are allowed                .allowCredentials(true);  // Allow credentials (such as cookies)    }
}

4. Customize CorsConfiguration

import ;
import ;
import ;
import ;

@Configuration
public class CustomCorsConfig implements WebMvcConfigurer {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        ((""));
        (("GET", "POST", "PUT", "DELETE"));
        (("*"));
        (true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        ("/**", configuration);

        return source;
    }
}

5. Actual combat

The following shows cross-domain in the project

Automatic configuration with @AutoConfiguration

Implement the WebMvcConfigurer interface and register custom cross-domain filters via FilterRegistrationBean CorsFilter and other filters

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
@AutoConfiguration
@EnableConfigurationProperties()
public class WebAutoConfiguration implements WebMvcConfigurer {

    /**
      * Create a CorsFilter filter bean and configure cross-domain settings
      *
      * @return FilterRegistrationBean configured with cross-domain settings
      */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterBean() {
        // Create CorsConfiguration object        CorsConfiguration config = new CorsConfiguration();
        (true);  // Allow credentials (such as cookies)        ("*"); // Allow requests from all sources (note: * is not usually recommended in production environments, and the allowed domains should be configured in specific configuration)        ("*"); // All request headers are allowed        ("*"); // Allow all HTTP methods (GET, POST, PUT, DELETE, etc.)
        // Create UrlBasedCorsConfigurationSource object        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        ("/**", config); // Configure cross-domain settings for all paths

         // Create and return a FilterRegistrationBean instance, register CorsFilter
         return createFilterBean(new CorsFilter(source), Integer.MIN_VALUE);
     }

     /**
      * Create a DemoFilter Bean, demo mode
      *
      * @return FilterRegistrationBean configured with DemoFilter
      */
    @Bean
    @ConditionalOnProperty(value = "demo", havingValue = "true")
    public FilterRegistrationBean<DemoFilter> demoFilter() {
        // Create and return a FilterRegistrationBean instance, register DemoFilter        return createFilterBean(new DemoFilter(), Integer.MIN_VALUE);
    }

    /**
      * Common method for creating FilterRegistrationBean instances
      *
      * @param filter instance that needs to be registered
      * @param order The execution order of the filter
      * @return FilterRegistrationBean instance with filter configured
      */
    public static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        (order);  // Set the order of filters        return bean;
    }
}

Summarize

How to deal with it Applicable scenarios Configuration location flexibility Configuration difficulty
@CrossOrigin Annotation Single controller or method Controller layer Low Low
Global configuration (WebMvcConfigurer) Global settings Configuration class (WebConfig) middle middle
Customize CorsConfiguration Complex cross-domain requirements Configuration class (CustomCorsConfig) high high

The above is personal experience. I hope you can give you a reference and I hope you can support me more.