How to get request URL in Spring Boot RestController
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
To get the request URL in a Spring Boot RestController, 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 (including scheme, host, and port) without directly depending on the servlet API.
The Direct Approach: HttpServletRequest
Spring automatically injects HttpServletRequest when you declare it as a method parameter. This is the most common way to access URL components:
For a request to http://localhost:8080/api/demo?page=1&size=10, this returns:
URL Component Methods Reference
HttpServletRequest provides separate methods for each part of the URL:
| Method | Returns | Example Value |
getRequestURL() | Full URL without query string | http://localhost:8080/api/demo |
getRequestURI() | Path portion only | /api/demo |
getScheme() | Protocol | https |
getServerName() | Host name | localhost |
getServerPort() | Port number | 8080 |
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 address | 127.0.0.1 |
Using ServletUriComponentsBuilder
Spring's ServletUriComponentsBuilder provides a cleaner, more testable alternative that does not require you to inject HttpServletRequest directly:
This pattern is standard for REST APIs that return a Location header after creating a resource. The builder automatically picks up the current request's scheme, host, port, and path.
Extracting Path Variables and Query Parameters
Spring MVC provides dedicated annotations for extracting specific parts of the URL without parsing strings manually:
| Annotation | Extracts | Example |
@PathVariable | Named segments from the URL path | /users/{id} extracts id |
@RequestParam | Query string parameters | ?page=2 extracts page |
@RequestHeader | HTTP header values | Authorization header |
@CookieValue | Cookie values | Session cookies |
@MatrixVariable | Matrix parameters (semicolon-separated) | /users;role=admin |
Handling Proxy and Load Balancer Headers
In production, your application typically sits behind a reverse proxy (Nginx, AWS ALB, Cloudflare). The original client URL uses HTTPS on port 443, but the request reaching your Spring Boot app uses HTTP on port 8080. getRequestURL() returns the internal URL, not the external one.
To get the original URL, configure Spring Boot to trust forwarded headers:
Then the proxy must send standard forwarding headers:
With this configuration, getRequestURL() and ServletUriComponentsBuilder will return the external URL (https://api.example.com/api/demo) instead of the internal one (http://localhost:8080/api/demo).
Using RequestContextHolder Outside Controllers
Sometimes you need the request URL in a service or utility class that is not a controller. Spring's RequestContextHolder gives you access to the current request from anywhere in the request-handling thread:
This approach is useful for logging interceptors, audit services, or error handlers that need URL context. However, it couples those classes to the servlet layer, which makes unit testing harder. Passing the URL as a method parameter is cleaner when possible.
Common Pitfalls
- Using
getRequestURL()behind a reverse proxy without configuringforward-headers-strategy. The returned URL will showhttp://localhost:8080instead of the public-facing URL. - Forgetting that
getQueryString()returnsnull(not an empty string) when there are no query parameters. ConcatenatinggetRequestURL() + "?" + getQueryString()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.HttpServletRequestin Spring Boot 3.x. Spring Boot 3 uses Jakarta EE, so the correct import isjakarta.servlet.http.HttpServletRequest. - Logging the full request URL (including query parameters) in production without sanitizing sensitive data. Query strings may contain tokens, API keys, or personally identifiable information.
Summary
- Use
HttpServletRequest.getRequestURL()for the full URL andgetRequestURI()for just the path. - Prefer
ServletUriComponentsBuilderfor building URLs programmatically, especially forLocationheaders in REST APIs. - Use
@PathVariableand@RequestParamto extract specific URL components instead of parsing strings. - Configure
server.forward-headers-strategy=nativewhen running behind a reverse proxy to get the correct external URL. - Always check for
nullfromgetQueryString()before concatenation.
Related reading
- How to get rid of Incremental annotation processing requested warning?
- How to get Spinner value?
- How to get Spring RabbitMQ to create a new Queue?
- How to get status code from webclient?
- How to get the concrete class name as a string?
- How to get the current date/time in Java
- How to get the current time in YYYY-MM-DD HHMISec.Millisecond format in Java?
- How to get the current working directory in Java?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.