Подтвердить что ты не робот

Как получить URL-адрес запроса в Spring Boot RestController

Я пытаюсь получить URL-адрес запроса в RestController. В RestController есть несколько методов, аннотированных с помощью @RequestMapping для разных URI, и мне интересно, как я могу получить абсолютный URL из аннотаций @RequestMapping.

@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;
   }
} 
4b9b3361

Ответ 1

Вы можете попробовать добавить дополнительный аргумент типа HttpServletRequest к методу getUrlValue():

@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
    String test = request.getRequestURI();
    return test;
}

Ответ 2

Позволяет получать любой URL-адрес вашей системы, а не только текущий.

import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))

URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()

Ответ 3

@RestController
@RequestMapping(value = "/my/absolute/url/{urlid}/tests")
public class AndroidAppController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getURLValue(@PathVariable("urlid") String urlid) {
        String getURL = urlid;
        return getURL;
    }

}