3

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.

smftr
  • 923
  • 3
  • 17
  • 31
  • This [post](https://stackoverflow.com/questions/1629102/root-url-of-the-servlet/37908450#37908450) answers my question, although looks ugly. – smftr Mar 13 '18 at 17:31

2 Answers2

4

The way to do it is using HttpServletRequest

@GetMapping(path="/")
public String index(HttpServletRequest httpServletRequest) {
    String link = httpServletRequest.getRequestURL();
    return "index";
}
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • this will return my current url in these mapping. i want to get another path instead – smftr Mar 13 '18 at 14:17
  • what do u meant by another path? – pvpkiran Mar 13 '18 at 14:17
  • edited my question, those links in both mapping will have same value – smftr Mar 13 '18 at 14:39
  • I upvoted this answer, because it answers the question as it is worded today (although the poster wanted in fact something else). *PS In fact it answers the posters question!* It helped me solve my issue. Thanks @pvpkiran – t0r0X May 02 '19 at 15:59
0

Below one line code should work.

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

or

ServletUriComponentsBuilder.fromCurrentContextPath().replacePath("/newPath").toUriString();
Sastrija
  • 3,284
  • 6
  • 47
  • 64