简体   繁体   English

如何在 Spring 引导控制器中获取给定路径的 URL?

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

In thymeleaf we have:在百里香叶中,我们有:

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

It becomes:它成为了:

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

I want to get the full URL given path like that in controller, like:我想在控制器中获取给定路径的完整 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";
}

EDITED This question can be interpreted as this:编辑这个问题可以解释为:

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

I think that APPLICATION_BASE_URL is ugly since i can deploy everywhere.我认为APPLICATION_BASE_URL很难看,因为我可以在任何地方部署。 I wonder there is a pretty function in spring boot or even java to get the base URL of my application.我想知道 spring boot 甚至 java 中是否有一个漂亮的函数来获取我的应用程序的基本 URL。

The way to do it is using HttpServletRequest方法是使用HttpServletRequest

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

Below one line code should work.下面一行代码应该可以工作。

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

or要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM