NRA*_*NRA 31 java spring spring-boot
我试图在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;
}
}
Run Code Online (Sandbox Code Playgroud)
Dee*_*pak 45
您可以尝试HttpServletRequest向该getUrlValue()方法添加其他类型的参数:
@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
Run Code Online (Sandbox Code Playgroud)
moh*_*nag 13
如果您不希望依赖Spring的HATEOAS或javax.*命名空间,请使用ServletUriComponentsBuilder获取当前请求的URI:
import org.springframework.web.util.UriComponentsBuilder;
ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();
Run Code Online (Sandbox Code Playgroud)
允许获取系统上的任何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()
Run Code Online (Sandbox Code Playgroud)
将类型参数添加UriComponentsBuilder到控制器方法中。Spring 将为您提供一个预先配置了当前请求的 URI 的实例,然后您可以自定义它(例如使用MvcUriComponentsBuilder.relativeTo相同的前缀指向不同的控制器)。
| 归档时间: |
|
| 查看次数: |
62144 次 |
| 最近记录: |