Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can java/scala/etc code tell when it is being run by tomcat?

Tags:

java

scala

tomcat

I have the data for my webapp in a database that is accessed differently from different places. There is no generic code that can just do it for both. So I want to know at run time which env I am in. In fact, the code to run really depends on whether it is run within or without tomcat, so I would like to detect this at runtime. How do I do this?

like image 814
Matt Roberts Avatar asked Dec 01 '25 19:12

Matt Roberts


1 Answers

This doesn't sound like something that the code should have to detect. Placing the burden of detecting an environment and acting differently within the same class is usually a less-than-ideal idea. If things need to be done differently, you should make a couple of different data access classes (which implement the same interface, and maybe share common code in an abstract class they both extend). Then, your web servlet would instantiate and use one class for its database access, and your non-web code would instantiate the other class for database access.

If for some reason you REALLY need to detect whether or not you're in the web abb within a single class, I suppose a somewhat clean way might be to set a System property when the server runs (I think it's -D command line option), and then look for that being set in your class. If it is, do the web logic, otherwise do the non-web logic.

like image 97
Kaleb Brasee Avatar answered Dec 04 '25 09:12

Kaleb Brasee