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:
1 2 3 |
String baseUrl = req.getRequestURL() .substring(0, req.getRequestURL().length() - req.getRequestURI().length()) + req.getContextPath(); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.huongdanjava.jakartaee.servlet; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/hello") public class HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String baseUrl = req.getRequestURL() .substring(0, req.getRequestURL().length() - req.getRequestURI().length()) + req.getContextPath(); // Writing the message on the web page PrintWriter out = resp.getWriter(); out.println(baseUrl); } } |
you will see the following results: