When working with web applications using Spring MVC or Spring Boot, sometimes we will need to get the base URL information of the application to do something. The base URL here is https://huongdanjava.com or https://google.com. To do this, you can use Spring’s ServletUriComponentsBuilder class.
In detail, this class has a method named fromRequestUri() with an object parameter of the HttpServletRequest class. We will get the base URL of the application with the object of this HttpServletRequest class, specifically as follows:
1 2 3 4 |
String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request) .replacePath(null) .build() .toUriString(); |
The fromRequestUri() method will return the schema (http or https), host, port, and context path of the application. Because our needs only need schema, host, and port, as you can see, we need to call replacePath() with a null value to remove this context path.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.huongdanjava.springboot; import jakarta.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @Controller public class HelloController { @RequestMapping("/hello") public String home(HttpServletRequest request) { String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request) .replacePath(null) .build() .toUriString(); System.out.println(baseUrl); return "home"; } } |
Result: