DonX DonX - 4 months ago 8x
Java Question

Root URl of the servlet

I want to get the root url of my web application from one of the servlet.

If I deploy my application in "" I want to get the root url like "".

Same thing if I deploy it in local tomcat server with 8080 port it should give


Can anyone tell me how to get the root URL of my web application from servlet?

public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String rootURL="";
//Code to get the URL where this servlet is deployed



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.