How to get request URL in Spring Boot RestController

后端 未结 4 1532
逝去的感伤
逝去的感伤 2020-12-05 01:47

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 wonde

相关标签:
4条回答
  • 2020-12-05 02:25

    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();
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-05 02:47

    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()
    
    0 讨论(0)
  • 2020-12-05 02:47

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

    0 讨论(0)
提交回复
热议问题