How to get request URL in Spring Boot RestController
I am trying to get the request URL in a RestController. The RestController has multiple methods annotated with @RequestMapping
for different URIs and I am wondering how I can get the absolute URL from the @RequestMapping
annotations.
@RestController
@RequestMapping(value = "/my/absolute/url/{urlid}/tests"
public class Test {
@ResponseBody
@RequestMapping(value "/",produces = "application/json")
public String getURLValue(){
//get URL value here which should be in this case, for instance if urlid
//is 1 in request then "/my/absolute/url/1/tests"
String test = getURL ?
return test;
}
}
Solution 1:
You may try adding an additional argument of type HttpServletRequest
to the getUrlValue()
method:
@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
Solution 2:
If you don't want any dependency on Spring's HATEOAS or javax.*
namespace, use ServletUriComponentsBuilder
to get URI of current request:
import org.springframework.web.util.UriComponentsBuilder;
ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();
Solution 3:
Allows getting any URL on your system, not just a current one.
import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()
Solution 4:
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).