Spring Boot
RestController
request URL
Java
web development

How to get the request URL in a Spring Boot RestController

Codemia Knowledge Hub ·

Inject HttpServletRequest into your handler method and call getRequestURL() for the full URL or getRequestURI() for just the path. Spring also provides ServletUriComponentsBuilder for building complete URLs (scheme, host and port included) without depending on the servlet API directly.

Reading the URL from HttpServletRequest

Spring injects HttpServletRequest automatically when you declare it as a method parameter:

java
1import jakarta.servlet.http.HttpServletRequest;
2import org.springframework.web.bind.annotation.GetMapping;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class UrlDemoController {
7
8    @GetMapping("/api/demo")
9    public String getUrlInfo(HttpServletRequest request) {
10        String fullUrl = request.getRequestURL().toString();
11        String uri = request.getRequestURI();
12        String queryString = request.getQueryString();
13        String method = request.getMethod();
14
15        return String.format(
16            "URL: %s | URI: %s | Query: %s | Method: %s",
17            fullUrl, uri, queryString, method
18        );
19    }
20}

For a request to http://localhost:8080/api/demo?page=1&size=10, this returns:

 
URL: http://localhost:8080/api/demo | URI: /api/demo | Query: page=1&size=10 | Method: GET

Methods for each part of the URL

java
1@GetMapping("/api/url-parts")
2public Map<String, String> getUrlParts(HttpServletRequest request) {
3    Map<String, String> parts = new LinkedHashMap<>();
4
5    parts.put("requestURL", request.getRequestURL().toString());
6    parts.put("requestURI", request.getRequestURI());
7    parts.put("scheme", request.getScheme());
8    parts.put("serverName", request.getServerName());
9    parts.put("serverPort", String.valueOf(request.getServerPort()));
10    parts.put("contextPath", request.getContextPath());
11    parts.put("servletPath", request.getServletPath());
12    parts.put("queryString", request.getQueryString());
13    parts.put("remoteAddr", request.getRemoteAddr());
14
15    return parts;
16}
MethodReturnsExample Value
getRequestURL()Full URL without query stringhttp://localhost:8080/api/demo
getRequestURI()Path portion only/api/demo
getScheme()Protocolhttps
getServerName()Host namelocalhost
getServerPort()Port number8080
getContextPath()Application context path/myapp or "" (root)
getServletPath()Path matched by the servlet/api/demo
getQueryString()Raw query string (null if none)page=1&size=10
getRemoteAddr()Client IP address127.0.0.1

Building URLs with ServletUriComponentsBuilder

ServletUriComponentsBuilder is a cleaner, more testable option that does not need HttpServletRequest injected:

java
1import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
2import org.springframework.http.ResponseEntity;
3import org.springframework.web.bind.annotation.PostMapping;
4import org.springframework.web.bind.annotation.RequestBody;
5import org.springframework.web.bind.annotation.RestController;
6import java.net.URI;
7
8@RestController
9public class ResourceController {
10
11    @PostMapping("/api/users")
12    public ResponseEntity<User> createUser(@RequestBody User user) {
13        User saved = userService.save(user);
14
15        // Build the location URI for the created resource
16        URI location = ServletUriComponentsBuilder
17            .fromCurrentRequest()
18            .path("/{id}")
19            .buildAndExpand(saved.getId())
20            .toUri();
21
22        return ResponseEntity.created(location).body(saved);
23    }
24}

This is the standard pattern for REST APIs that return a Location header after creating a resource. The builder picks up the current request's scheme, host, port and path.

java
1// Other useful builder methods
2String currentUrl = ServletUriComponentsBuilder
3    .fromCurrentRequestUri()
4    .toUriString();
5// "http://localhost:8080/api/users"
6
7String baseUrl = ServletUriComponentsBuilder
8    .fromCurrentContextPath()
9    .toUriString();
10// "http://localhost:8080"

Path variables and query parameters

Spring MVC annotations extract specific parts of the URL so you do not have to parse strings:

java
1@GetMapping("/api/users/{userId}/orders/{orderId}")
2public String getOrder(
3        @PathVariable Long userId,
4        @PathVariable Long orderId,
5        @RequestParam(defaultValue = "1") int page,
6        @RequestParam(required = false) String sort,
7        HttpServletRequest request) {
8
9    // Path variables are extracted automatically
10    // Query params are extracted automatically
11    // Use HttpServletRequest only when you need the raw URL
12
13    String fullUrl = request.getRequestURL() + "?" + request.getQueryString();
14    return String.format("User %d, Order %d, Page %d, URL: %s",
15        userId, orderId, page, fullUrl);
16}
AnnotationExtractsExample
@PathVariableNamed segments from the URL path/users/{id} extracts id
@RequestParamQuery string parameters?page=2 extracts page
@RequestHeaderHTTP header valuesAuthorization header
@CookieValueCookie valuesSession cookies
@MatrixVariableMatrix parameters (semicolon-separated)/users;role=admin

Getting the external URL behind a proxy

In production the app usually sits behind a reverse proxy (Nginx, AWS ALB, Cloudflare). The client uses HTTPS on port 443, but the request reaching Spring Boot uses HTTP on port 8080, so getRequestURL() returns the internal URL.

Configure Spring Boot to trust forwarded headers:

properties
# application.properties
server.forward-headers-strategy=native

And have the proxy send the standard forwarding headers:

nginx
1# Nginx configuration
2proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
3proxy_set_header X-Forwarded-Proto $scheme;
4proxy_set_header X-Forwarded-Host $host;
5proxy_set_header X-Forwarded-Port $server_port;

Now getRequestURL() and ServletUriComponentsBuilder return the external URL (https://api.example.com/api/demo) instead of the internal one (http://localhost:8080/api/demo).

java
1// Manually reading forwarded headers (for debugging)
2@GetMapping("/api/debug-headers")
3public Map<String, String> debugHeaders(HttpServletRequest request) {
4    Map<String, String> info = new LinkedHashMap<>();
5    info.put("requestURL", request.getRequestURL().toString());
6    info.put("X-Forwarded-For", request.getHeader("X-Forwarded-For"));
7    info.put("X-Forwarded-Proto", request.getHeader("X-Forwarded-Proto"));
8    info.put("X-Forwarded-Host", request.getHeader("X-Forwarded-Host"));
9    return info;
10}

Getting the URL outside a controller with RequestContextHolder

In a service or utility class, RequestContextHolder gives access to the current request from anywhere in the request-handling thread:

java
1import org.springframework.web.context.request.RequestContextHolder;
2import org.springframework.web.context.request.ServletRequestAttributes;
3import jakarta.servlet.http.HttpServletRequest;
4
5public class RequestUtils {
6
7    public static String getCurrentRequestUrl() {
8        ServletRequestAttributes attrs =
9            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
10        if (attrs == null) {
11            throw new IllegalStateException("No current request context");
12        }
13        HttpServletRequest request = attrs.getRequest();
14        String query = request.getQueryString();
15        String url = request.getRequestURL().toString();
16        return query != null ? url + "?" + query : url;
17    }
18}

This helps in logging interceptors, audit services or error handlers. It couples those classes to the servlet layer, though, which makes unit testing harder. Passing the URL as a method parameter is cleaner when possible.

Mistakes when reading the request URL

  • Using getRequestURL() behind a reverse proxy without forward-headers-strategy. You get http://localhost:8080 instead of the public URL.
  • Forgetting that getQueryString() returns null, not an empty string, when there are no query parameters. getRequestURL() + "?" + getQueryString() then produces ...?null.
  • Using getRequestURL() when you only need the path. getRequestURI() is cheaper and avoids scheme/host/port coupling, which makes testing easier.
  • Importing javax.servlet.http.HttpServletRequest in Spring Boot 3.x. Spring Boot 3 uses Jakarta EE, so the import is jakarta.servlet.http.HttpServletRequest.
  • Logging full URLs with query parameters in production without sanitizing. Query strings may contain tokens, API keys or personally identifiable information.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms