Get the base URL from the object of the HttpServletRequest class in Jakarta EE

I have shown you how to Get the base URL in the JSP page and Get base URL in Controller in Spring MVC and Spring Boot. In addition to the above methods, to be able to get the base URL of a Java web application from anywhere, you can also use the object of the HttpServletRequest class as follows:

The getRequestURL() method will return the full request URL excluding the query string that the user requested to the application.

For example, if the user requests to the URL http://localhost:8080/hello, the getRequestURL() method will return the value “http://localhost:8080/hello”! If the user requests to http://localhost:8080/hello?a=1, the getRequestURL() method will only return the value of http://localhost:8080/hello.

The getRequestURI() method will return the part of the request URL after the host address and port, excluding the query string.

For the above example, the getRequestURI() method will return “/hello”.

The getContextPath() method is for getting the path, usually the application’s deployment directory.

Normally applications will be deployed using the context path as root, in this case, the value of the returned context path will be empty. As in my example above, the context path will be empty!

Some applications are deployed to JBoss or Tomcat. To access the application, we need to include the name of the application deployment directory, for example, http://localhost:8080/jakarta-ee/hello. In this case, the context path will be “jakarta-ee”.

The base URL we need to get will include protocol, host, port, and context path, so as you can see in the base URL code above, we need to remove the value of the request URI in the request URL first, then plus with the context path, will get the value of base URL.

If you now run the following example:

you will see the following results:

Add Comment