Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I tell if I'm running in a Servlet container  RSS feed

 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got a library that I use all over the place. Sometimes in web apps (tomcat, glassfish, etc.) and sometimes stand alone.

When running under a container, I want to let the container handle the database connection pool. When running standalone, I have to provide the functionality in my
own code.

So I need to be able to tell if a servlet container is running this code.

I'd like a nice, clean way to do this.

I can think of some ugly ones, like iterating through all of the classes loaded by the ClassLoader, and using reflection to see if any "marker" classes are loaded.
I can probably think of other ugly ones as well. But clean would be better.

 
Tim Moores
Saloon Keeper
Posts: 3511
77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Examining the contents of new Exception().getStackTrace() amounts to the same as your ClassLoader idea, but with less coding effort on your part. The ugliness of that approach is in the eye of the beholder...
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65824
134
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming that it's "close enough" if the servlet APi is in the classpath, why not just try to load a servlet API class and see if it loads?

Perhaps: Class.forName("javax.servlet.http.HttpServlet");

(Though personally I'd just make it a parameter or configuration setting.)
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This sure seems fairly clean. Works in my initial testing too. Thanks @bear

 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No need for the null check. Class.forName never returns null. It either returns a Class object or throws a ClassNotFoundException.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!