Root URl of the servlet
jakarta-ee, java
Solution
You do realize that the URL client sees (and/or types into his browser) and the URL served by the container your servlet is deployed on can be very different?
In order to get the latter, though, you have a few methods available on HttpServletRequest:
- You can either call `getScheme()`, `getServerName()`, `getServerPort()` and `getContextPath()` and combine them using appropriate separators
- OR you can call `getRequestURL()` and remove `getServletPath()` and `getPathInfo()` from it.
Problem
I want to get the root url of my web application from one of the servlet. If I deploy my application in "www.mydomain.com" I want to get the root url like "http://www.mydomain.com". Same thing if I deploy it in local tomcat server with 8080 port it should give `http://localhost:8080/myapp` Can anyone tell me how to get the root URL of my web application from servlet? ``` public class MyServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String rootURL=""; //Code to get the URL where this servlet is deployed } } ```