Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if running in servlet container or standalone

I have a simple problem: I want to configure an object differently based on whether the object is instantiated within a servlet container, or whether it is instantiated in a stand alone app.

The object is a database connection, and I care about setting query timeouts.

The first solution that I can come up with is:

if (insideServletContainer(this.getClass().getClassLoader()) { 
  /// do some servlet specific config
}
else {
 /// do some standalone config
}

The question is, of course, can I write a reliable method of telling whether the class was loaded within a servlet container. It feels like a hack at best.

The second option is to assume that the default case is a stand alone instantiation, set defaults based on stand-alone configuration, and override them within the servlet context.

So, to sum up my question is: Do you know of a good/reliable mechanism if the class was loaded from within a servlet container? If not, I will have to take the second route.

Nick

like image 286
Nick Hristov Avatar asked Jun 04 '10 18:06

Nick Hristov


Video Answer


3 Answers

This seems like a really bad idea. Instead, why don't you allow the class to take parameters, then let the container or app configure it appropriately?

like image 81
Zak Avatar answered Oct 07 '22 20:10

Zak


Setting aside whether or not this is a good idea, I'd suggest looking up java:comp/env, which is only going to be available in an EE server:

try {
  new InitialContext().lookup("java:comp/env");
  /// do some servlet specific config
} catch (NamingException ex) {
  /// do some standalone config
}
like image 35
Brett Kail Avatar answered Oct 07 '22 19:10

Brett Kail


An alternate way to do this sort of thing is to have the configuration injected into this class by some sort of bootstrap loader.

In a standalone version, this would be done by the main() method (or something called from it).

In a webapp version, this would be done by a listener or filter invoked configured within the web.xml.

Dependency injection is useful here as it removes the need for your application to check these sorts of things; instead the application is given what it needs.

like image 4
matt b Avatar answered Oct 07 '22 19:10

matt b