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:
@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. I wonder there is a pretty function in spring boot or even java to get the base URL of my application.
The way to do it is using 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.