![](/img/trans.png)
[英]Spring Boot - How to get all request params in a map in Spring RestController?
[英]How to get request URL in Spring Boot RestController
我正在尝试在 RestController 中获取请求 URL。 对于不同的 URI,RestController 有多个用@RequestMapping
注释的方法,我想知道如何从@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()
将类型为UriComponentsBuilder
的参数添加到您的控制器方法中。 Spring 将为您提供一个使用当前请求的 URI 预配置的实例,然后您可以对其进行自定义(例如通过使用MvcUriComponentsBuilder.relativeTo
指向使用相同前缀的不同控制器)。
@SpringBootApplication
@RestController
public class DataStore {
public static void main(String[] args) {
SpringApplication.run(DataStore.class, args);
}
@RequestMapping(path = "api/v1/student/{studentId}")
public int getURLValue(@PathVariable("studentId") int studentId){
System.out.println("studentId is " + studentId);
return studentId;
}
}
如果您已经在path
设置了 URL,那么您已经知道您的 url 的“前缀”。 您只需要知道可以使用@PathVariable
获取的 url 中的参数
@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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.