Handling Cross‑Origin Issues with @CrossOrigin, Spring Cloud Gateway, and HttpClient

This article explains why browsers enforce same‑origin policies, presents common CORS solutions such as the @CrossOrigin annotation, gateway integration with Spring Cloud Gateway, and using HttpClient, and provides detailed configuration and code examples for implementing these approaches in a Java backend project.

Architect
Architect
Architect
Handling Cross‑Origin Issues with @CrossOrigin, Spring Cloud Gateway, and HttpClient

Because browsers enforce the same‑origin policy, requests from different origins (different ports, protocols, or domains) are blocked, leading to cross‑origin (CORS) problems.

Common CORS solutions include adding the @CrossOrigin annotation in controller layers, using an HTTP client that bypasses the browser, or routing requests through a gateway.

@CrossOrigin annotation : Adding this annotation to a controller enables cross‑origin requests for that endpoint.

Gateway integration : Spring Cloud Gateway replaces Netflix Zuul and provides unified routing, predicates, and filters. It supports routing IDs, URIs, and predicate definitions to forward requests to target services. Filters (Gateway Filter and Global Filter) can modify requests and responses.

Example gateway dependency configuration:

<dependencies>
    <!-- Public module dependency -->
    <dependency>
        <groupId>com.lzq</groupId>
        <artifactId>service_utils</artifactId>
        <version>0.0.1‑SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring‑cloud‑starter‑gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring‑cloud‑starter‑alibaba‑nacos‑discovery</artifactId>
    </dependency>
</dependencies>

Gateway configuration (application.yml or properties):

server.port=9090
spring.application.name=service‑gateway
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8888
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.routes[0].id=service‑hosp
spring.cloud.gateway.routes[0].uri=lb://service‑hosp
spring.cloud.gateway.routes[0].predicates=Path=/*/hosp/**
... (additional routes)

Spring Cloud Gateway routing works by matching request URLs against route definitions; if a predicate evaluates to true, the request is forwarded to the configured service.

CORS configuration class (Java):

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

If @CrossOrigin was previously used, it should be removed when the global CORS filter is applied.

HttpClient usage for cross‑system communication or crawling:

public class HttpTest {
    @Test
    public void test1() throws Exception {
        String url = "https://www.badu.com";
        URL url1 = new URL(url);
        URLConnection urlConnection = url1.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        InputStream is = httpURLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Using Apache HttpClient:

CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://www.baidu.com");
CloseableHttpResponse response = client.execute(httpGet);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
client.close();

Helper classes such as HttpRequestHelper and HttpUtil encapsulate request building, parameter encoding, and response handling, enabling services to call external APIs (e.g., saving hospital data) and process JSON results.

Finally, the article includes a sample Spring MVC controller that receives hospital data, converts request parameters to a JSON object, and persists it via a service, demonstrating end‑to‑end cross‑origin communication between front‑end, gateway, and back‑end services.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaSpring BootCORSSpring Cloud GatewayHttpClient
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.