How to get request URL in Spring Boot RestController

JavaSpringSpring Boot

Java Problem Overview


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;
   }
} 

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNRAView Question on Stackoverflow
Solution 1 - JavaDeepakView Answer on Stackoverflow
Solution 2 - JavamohamnagView Answer on Stackoverflow
Solution 3 - JavaCyvaView Answer on Stackoverflow
Solution 4 - Javachrylis -cautiouslyoptimistic-View Answer on Stackoverflow