如何在Spring Boot RestController中获取请求URL

2022-08-31 17:10:08

我正在尝试在 RestController 中获取请求 URL。RestController具有针对不同URI注释的多个方法,我想知道如何从注释中获取绝对URL。@RequestMapping@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;
   }
} 

答案 1

您可以尝试向该方法添加其他类型参数:HttpServletRequestgetUrlValue()

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

答案 2

如果您不希望对Spring的HATEOAS或命名空间进行任何依赖,请使用以获取当前请求的URI:javax.*ServletUriComponentsBuilder

import org.springframework.web.util.UriComponentsBuilder;

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

推荐