如何在Spring Boot RestController中获取请求URL
我试图在RestController中获取请求URL。 RestController有多个使用@RequestMapping
注释的方法用于不同的URI,我想知道如何从@RequestMapping
注释中获取绝对URL。
@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; } }
您可以尝试向getUrlValue()
方法添加类型为HttpServletRequest
的附加参数:
@RequestMapping(value ="/",produces = "application/json") public String getURLValue(HttpServletRequest request){ String test = request.getRequestURI(); return test; }
如果您不希望依赖Spring的HATEOAS或javax.*
命名空间,请使用ServletUriComponentsBuilder
获取当前请求的URI:
import org.springframework.web.util.UriComponentsBuilder; ServletUriComponentsBuilder.fromCurrentRequest(); ServletUriComponentsBuilder.fromCurrentRequestUri();
允许获取系统上的任何URL,而不仅仅是当前的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()
@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; } }