Handling Cross‑Origin Requests with Spring Cloud Gateway, @CrossOrigin Annotation, and HttpClient
The article explains why browsers enforce same‑origin policies, then presents three practical ways to solve cross‑origin issues in a Spring Boot backend—using the @CrossOrigin annotation, routing through Spring Cloud Gateway, and making server‑side requests with HttpClient—accompanied by configuration examples and full code snippets.
This article explains why cross‑origin problems occur in web applications and introduces three common solutions for a Spring Boot backend: the @CrossOrigin annotation, integration of a gateway, and using HttpClient for server‑side requests.
Browsers implement a same‑origin policy for security; requests that originate from a different port, protocol, or domain are blocked, which leads to cross‑origin errors.
Common solutions :
Add the @CrossOrigin annotation to controller classes or methods.
Use a gateway such as Spring Cloud Gateway to centralise routing, predicates and filters.
Perform the request on the server side with HttpClient, bypassing the browser’s restrictions.
1. @CrossOrigin annotation
Adding @CrossOrigin on a controller method enables CORS for that endpoint, eliminating the need for client‑side workarounds.
2. Spring Cloud Gateway integration Spring Cloud Gateway replaces Netflix Zuul and provides unified routing, predicate matching, and filter chains (Gateway Filter and Global Filter) for security, monitoring, rate‑limiting, etc.
Key concepts:
Route : defined by an ID, URI, predicates and filters.
Predicate : a function that decides whether a request matches a route (e.g., Path=/**/hosp/**).
Filter : modifies request/response; can be a Gateway Filter (route‑specific) or Global Filter (applies to all routes).
Example application.yml configuration:
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/**
spring.cloud.gateway.routes[1].id=service-cmn
spring.cloud.gateway.routes[1].uri=lb://service-cmn
spring.cloud.gateway.routes[1].predicates=Path=/**/cmn/**
spring.cloud.gateway.routes[2].id=service-user
spring.cloud.gateway.routes[2].uri=lb://service-hosp
spring.cloud.gateway.routes[2].predicates=Path=/**/userlogin/**Startup class:
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}After deploying the gateway, modify the front‑end .env file to point to the gateway port, and the gateway will forward requests while handling CORS.
3. HttpClient usage
Two approaches are shown: native HttpURLConnection and Apache HttpClient. The native example demonstrates opening a URL, reading the response stream, and printing each line. The Apache example outlines creating a client, building a request (GET or POST), executing it, extracting headers and entity, and finally releasing the connection.
Dependency for Apache HttpClient:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>Test code snippet:
CloseableHttpClient client = HttpClients.createDefault();
String url = "https://www.baidu.com";
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = client.execute(httpGet);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
client.close();Finally, the article shows how to call a platform API from the service layer using a helper class ( HttpRequestHelper) that builds a POST body from a Map, sends it via HttpUtil.doPost, and parses the JSON response.
Overall, the guide provides a complete workflow for solving cross‑origin issues in a Java backend: enable CORS at the controller level, optionally route through a gateway with proper predicates and filters, and perform server‑side HTTP calls when the browser cannot be used.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
