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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37710557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:35:31  来源:igfitidea点击:

How to get request URL in Spring Boot RestController

javaspringspring-boot

提问by NRA

I am trying to get the request URL in a RestController. The RestController has multiple methods annotated with @RequestMappingfor different URIs and I am wondering how I can get the absolute URL from the @RequestMappingannotations.

我正在尝试在 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;
   }
} 

回答by Deepak

You may try adding an additional argument of type HttpServletRequestto the getUrlValue()method:

您可以尝试HttpServletRequestgetUrlValue()方法中添加一个额外的类型参数:

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

回答by Cyva

Allows getting any URL on your system, not just a current one.

允许获取系统上的任何 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()

回答by mohamnag

If you don't want any dependency on Spring's HATEOAS or javax.*namespace, use ServletUriComponentsBuilderto get URI of current request:

如果您不想依赖 Spring 的 HATEOAS 或javax.*命名空间,请使用ServletUriComponentsBuilder获取当前请求的 URI:

import org.springframework.web.util.UriComponentsBuilder;

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

回答by chrylis -cautiouslyoptimistic-

Add a parameter of type UriComponentsBuilderto your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeToto point at a different controller using the same prefix).

将类型参数添加UriComponentsBuilder到您的控制器方法中。Spring 将为您提供一个使用当前请求的 URI 预配置的实例,然后您可以对其进行自定义(例如MvcUriComponentsBuilder.relativeTo使用相同前缀指向不同的控制器)。