user321974
user321974

Reputation: 11

Loading a webapp (or even just a listener) from Tomcat 9 context.xml

I have a class that I want to load and run a method once before ANY of the webapps are initialized.

Since I could not find a way to do it, I figured I could write a ServletContextListener, put it in an exploded WAR and deploy/initialize it before the other webapps. As the other webapps are all exploded WARs and I read that I could deploy this one first by declaring it in context.xml.

Although I tried to interpret the many threads on the matter, blogs and Tomcat's docs... I clearly understood it wrong. The main problem is that I could not find a single complete example. I also saw references to people adding a context.xml inside of the war itself, but that seems to be for a different purpose.

This is what I did:

<Context path="/webBootstrap" docBase="D:\work\app-j11t9-test\webBootstrap" />

And it made Tomcat really mad, throwing lots of errors for every single webapp. I am sure that those in the know see what I did and roll on the floor laughing.

So, how do I do it right? (to run that listener ONCE, before all of the other webapps initialize)

Upvotes: 0

Views: 601

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 16635

Sounds like you want a LifecycleListener. The compiled code (JAR or .class in an appropriate directory structure) needs to be placed in $CATALINA_HOME/lib and you configure it in server.xml. There are already several such listeners defined in server.xml and you can look at the source of each of them for inspiration if required.

Upvotes: 0

ru4ert
ru4ert

Reputation: 1179

Do you have something like a base Class? In this class you make a static variable.

E.g.

public class BaseClass {

public static boolean initCodeRunned = false;

 public static void doInit(){
   if(!BaseClass.initCodeRunned){ 
    // Do your code

    // After the init was success, you can set the initCodeRunned to true.
    BaseClass.initCodeRunned = true;
   } 
 }
}

Afterward there a two ways to go on.

  • First, you make in your very fist line of the index.jsp the call to the BaseClass.init().

  • Or you make a SessionListener. In the Session Listener's sessionCreated(), you make the call to the BaseClass.init() function.

Upvotes: -1

Related Questions