Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "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      } } 
like image 375
DonX Avatar asked Oct 27 '09 06:10

DonX


People also ask

How do I find the root url?

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).

What is servlet in url?

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.

What is the root directory used for servlet?

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.

What is servlet context root?

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 "".


1 Answers

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.
like image 105
ChssPly76 Avatar answered Sep 17 '22 17:09

ChssPly76