tags:

views:

354

answers:

2

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

      }

   }
+2  A: 

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.
ChssPly76
I believe, `myapp` is a servlet name/path, in OP's example. What say you?
Adeel Ansari
"myapp" is a context path
ChssPly76
+2  A: 

Generally, you can't obtain the URL; but, there are workarounds for specific cases. See Finding your application’s URL with only a ServletContext

janko