簡體   English   中英

如何在 Spring 引導控制器中獲取給定路徑的 URL?

[英]How to get URL given path in Spring boot Controller?

在百里香葉中,我們有:

<a th:href="@{/somepath}">Link</a>

它成為了:

<a href="http://hostname:port/somepath">Link</a>

我想在控制器中獲取給定路徑的完整 URL,例如:

@GetMapping(path="/")
public String index(SomeInjectedClass cls) {
    String link = cls.someMethod('/somepath');
    // expected, link = http://hostname:port/somepath
    return "index";
}

@GetMapping(path="/home")
public String home(SomeInjectedClass cls) {
    String link = cls.someMethod('/somepath');
    // expected, link = http://hostname:port/somepath
    return "home";
}

編輯這個問題可以解釋為:

public static String APPLICATION_BASE_URL = "http://hostname:port";
function someMethod(String method){
    return APPLICATION_BASE_URL + method;
}

我認為APPLICATION_BASE_URL很難看,因為我可以在任何地方部署。 我想知道 spring boot 甚至 java 中是否有一個漂亮的函數來獲取我的應用程序的基本 URL。

方法是使用HttpServletRequest

@GetMapping(path="/")
public String index(HttpServletRequest httpServletRequest) {
    String link = httpServletRequest.getRequestURL();
    return "index";
}

下面一行代碼應該可以工作。

ServletUriComponentsBuilder.fromCurrentContextPath().path("/newPath").toUriString();

要么

ServletUriComponentsBuilder.fromCurrentContextPath().replacePath("/newPath").toUriString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM