tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Mark Eggers <>
Subject Re: server.xml hostname from ServletContext
Date Mon, 01 Oct 2012 16:11:06 GMT
On 10/1/2012 8:38 AM, Aggarwal, Ajay wrote:
> Is the configured hostname available in ServletContext? I see it in
> debugger, but I don't see any method to access it from ServletContext
> class. I am using virtual hosts and need this value inside my
> ServletContextListener ::contextInitialized() call back.
> Thanks.
> -Ajay

I've not found a convenient way to manage this. Getting the host name 
when you are using multiple Host elements in your server.xml appears to 
return the host you're running on (and not the Host element name or alias).

The easiest way I've found to do this is as follows.

1. Create a context.xml.default

In each CATALINA_BASE/conf/[engine]/[hostname] create an XML file called 
context.xml.default. [engine] is usually Catalina. This default context 
gets added to all web applications in that [hostname].

2. Add a JNDI environment resource to the context.xml.default

In each context.xml.default file, add a resource something like the 

     <Environment name="hostname" value="your-hostname-goes-here"
                  type="java.lang.String" override="false"/>

3. In your servlet context listener, read the information

Something like this - and then do with it what you want.

// lots of imports omitted

ServletContext sc = sce.getServletContext();
try {
     Context initCtx = new InitialContext();
     Context envCtx = (Context) initCtx.lookup("java:comp/env");
     String hostname = (String) envCtx.lookup("hostname");
     if (hostname != null) {
         sc.setAttribute("hostname", hostname); // or anything else
} catch (NamingException ex) {
     // do something nice about logging here

See the following documentation for Tomcat 6 (which is where I've tried 

I suspect it's the same in Tomcat 7. Read the appropriate documentation 
to find out.

The nice thing about using JNDI is that it's server-agnostic. If you end 
up trying to fish out the Host name or Alias element from Tomcat's 
internal code, then you have two problems.

1. It's Tomcat-specific

What happens when your code is run on another server?

2. Tomcat devs can change the internal architecture

Although I don't imagine that this part of the code will change much 
(haven't looked at SVN, and I'm not a developer), this type of tight 
coupling doesn't seem to be prudent.

. . . . just my two cents

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message