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 } }
You can determine your server's root URL by browsing to a page on your website and observing the address in the location/address entry field of the browser. The root URL is the section between the colon-slash-slash (://) and the next slash (/), omitting any port number (:portno).
Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.
The WEB-INF/classes directory is used for servlets and utility classes that can be used by the web application. If the Java classes are scoped within a Java package, the classes directory must contain the proper subdirectories that match the package name.
The context path is the portion of the request URI that is used to select the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "".
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:
getScheme()
, getServerName()
, getServerPort()
and getContextPath()
and combine them using appropriate separatorsgetRequestURL()
and remove getServletPath()
and getPathInfo()
from it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With