73

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

4 Answers 4

95

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for reply and example. I know this method but was wondering if there is way to get url info using any properties in controller level but seems like this is the correct way.
Where is HttpServletRequest imported from?
javax.servlet.http.HttpServletRequest
This does not include parameters
38

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.servlet.support.ServletUriComponentsBuilder;

ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();

1 Comment

Cleanest solution. Can also be used outside of a Controller.
9

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

2 Comments

This answer works perfectly, but is it possible to do without having a HATEAOS dependency? Although all the methods I tried depend on the request, one way or another, and I don't have that in my scenario.
Where does this go? How?
5

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

1 Comment

I'd never heard of MvcUriComponentsBuilder before! It's so useful for RESTful controllers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.