Let a webapp be aware of the host and port it is being hosted on

1k views Asked by At

I host my java/jsp based webapps using tomcat 7.0. I would like to make my webapps be able to invoke requests from other webapps (on the same machine). To do this, they need to know the url from which they can access each other. I don't want to do this hardcoded (either in the code, or in a config file), but I don't see how to let each webapp be aware of their own access-url. Specifically, I would like the webapps to be aware of the following information:

protocol: http or https host: my.machine.com port: 1234 webapp context: webappName

With this information They could build their access url: http://my.machine.com:1234/webappName/

Of course Tomcat knows this information, but how can I push this information into my java code? I was thinking about making a servletListener which stores this information in memory on startup of the app, but I only found a way to get the webapp context with this code:

public void contextInitialized(ServletContextEvent servletContextEvent)
{
    ServletContext servletContext = servletContextEvent.getServletContext();        
    String webappContext = servletContext.getContextPath();
}
1

There are 1 answers

2
Bhaskara On BEST ANSWER

All the information can be obtained from HttpServletRequest.

Protocol:  request.getProtocol(); // Returns HTTP/1.1
Scheme: request.getScheme(); //returns http or https
Context: request.getContextPath(); // return webappname
Request URL: request.getRequestURL() //return http://my.machine.com:1234/webappName/servletpath
Request URI: request.getRequestUri() // returns /servletpath
Host: request.getLocalAddr(); // returns 0:0:0:0:0:0:0:1 (if server is running on localhost)
Port: request.getLocalPort(); // returns 1234
Hostname: request.getServerName(); // returns my.machine.com
Port: request.getServerPort(); // returns 8080