MichelReap
MichelReap

Reputation: 5770

How to know web application URL in Servlet application

I want to be able to access, statically (or globally somehow) the URL of my own application, that is, I want to know the URL of the root context path, so for instance if it is in:

http://example.com/contextroot/

I want to be able to get this information in any part of my app. So I guess I have to obtain this information after the application is initialized, my instincts tells me it is somewhere among listeners or Servlet interceptors, but I'm not sure where can I store this information in, for example, a Singleton.

Upvotes: 2

Views: 1098

Answers (2)

mmulholl
mmulholl

Reputation: 291

A web application does not define a host and port for itself, it defines the context root and all of the resources available at the context root. The host and port are part of the server config and not available through any servlet api's other than as part of an inbound request through the request object using such methods as :

 HttpServletRequest.getRequestURL()
 ServletRequest.getLocalName()
 ServletRequest.getLocalPort()

If you do not want to set up a variable as part of a request the other option is a ServletContextListener - you can set a ServletContext attribute in the contextInitialized method but you will need to read the hostname and port from other means. Requests can get to the attribute using:

ServelRequest.getServletContext().geAttribute()

Upvotes: 0

lunatikz
lunatikz

Reputation: 736

I had done something similar a few years ago. But there was a little logic involved.

Per

request.getRequestURL()

you can obtain actually a full path of your application, but if you do this in servlet, your result would be something like this.

http://<server:port>/<contextname>/<servletName>

What I've done, was just parsing the string, and replacing servletName with empty string.

To make this globally available, i had used the servlets context attributes.

getServletContext().setAttribute(key, value)

in Servlets you can access them globally via the context object.

in jsp, i had used jstl and accessed this way

${applicationScope.key}

I think there might be better options to do this, but this had worked for me

Upvotes: 1

Related Questions