SoFunction
Updated on 2025-04-05

Java backend configuration allows cross-domain approach

1. Use @CrossOrigin annotation (Spring MVC)

If you are using Spring MVC or Spring Boot, the easiest way is to use it directly on the controller class or method@CrossOriginAnnotation to allow cross-domain requests from specific sources.

import ;
import ;
import ;

@RestController
@CrossOrigin(origins = "") // Allow cross-domain requests frompublic class MyController {

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

You can specify multiple sources, or use*to allow all sources (but not recommended for production):

@CrossOrigin(origins = "*") // All sources are allowed

2. Configure global CORS support (Spring Boot)

In order to configure CORS rules uniformly throughout the application, rather than by controller or method configuration, it can be implementedWebMvcConfigurerInterface and define the global CORS configuration in it.

import ;
import ;
import ;
import ;

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                ("/**") // Applied to all paths                    .allowedOrigins("") // Allowed sources                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // Allowed methods                    .allowCredentials(true) // Whether to allow sending credential information (such as cookies)                    .maxAge(3600); // The validity period of the pre-flight request (seconds)            }
        };
    }
}

3. Configure CORS using Spring Security (if Spring Security is used)

If your application uses Spring Security, you also need to make sure CORS support is enabled in the security configuration as well.

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

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ().and()
            .csrf().disable(); //Enable or disable CSRF protection as needed    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        (true);
        ("");
        ("*");
        ("*");
        ("/**", config);
        return new CorsFilter(source);
    }
}

4. Manually set the response header (Servlet API)

For projects that do not use the Spring framework, you can manually set the response header in the Servlet to allow cross-domain requests.

import ;
import ;
import ;
import ;
import ;

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // Set CORS response header        ("Access-Control-Allow-Origin", "");
        ("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        ("Access-Control-Max-Age", "3600");
        ("Access-Control-Allow-Headers", "Content-Type, Authorization");

        // Process pre-flight request        if ("OPTIONS".equalsIgnoreCase(())) {
            (HttpServletResponse.SC_OK);
        } else {
            //Requests are processed normally            ().print("Data from server");
        }
    }
}

Summarize

Choose the most suitable way to configure CORS according to your technology stack and requirements.

Whether it is through annotation, global configuration, or manually setting the response header, it is key to make sure you correctly specify the allowed sources, methods, and other necessary parameters.

If you are using Spring framework, especially Spring Boot, it is recommended to use it@CrossOriginAnnotation or global configuration, as they are simpler and easier to maintain.

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