Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

@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.

like image 354
smftr Avatar asked Sep 02 '25 06:09

smftr


1 Answers

The way to do it is using HttpServletRequest

@GetMapping(path="/")
public String index(HttpServletRequest httpServletRequest) {
    String link = httpServletRequest.getRequestURL();
    return "index";
}
like image 92
pvpkiran Avatar answered Sep 04 '25 21:09

pvpkiran