Get base URL in Controller in Spring MVC and Spring Boot

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:

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:

Result:

2.6/5 - (5 votes)

Add Comment