4

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.

1
  • This post answers my question, although looks ugly. Commented Mar 13, 2018 at 17:31

2 Answers 2

5

The way to do it is using HttpServletRequest

@GetMapping(path="/")
public String index(HttpServletRequest httpServletRequest) {
    String link = httpServletRequest.getRequestURL();
    return "index";
}
Sign up to request clarification or add additional context in comments.

4 Comments

this will return my current url in these mapping. i want to get another path instead
what do u meant by another path?
edited my question, those links in both mapping will have same value
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
0

Below one line code should work.

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

or

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

4 Comments

This will only append a path. I think the TO want a replacing procedure.
@Snickbrack, Please check the Edited section of the question and sample there. This solution gives same result which OP is asking
No, I have tested it and the .path-Method appends the /newPath instead of replacing it.
@Snickbrack, I'm getting the expected results when I tried from my side. You can try .replacePath() instead of .path()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.