2

In my Vaadin app, for servletInitialized() method in my servlet class to be called to start my app, I have to make at least one request for the web app url via a browser.

I am using Intellij IDEA and I am starting my web app in a local tomcat instance with Tomcat Server run configuration of IDEA.

Is it possible to start the servlet as soon as the war file is deployed, without a need to make a request?

worpet
  • 3,788
  • 2
  • 31
  • 53
Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179

2 Answers2

13
<servlet>
    ...
    <load-on-startup>1</load-on-startup>
</servlet> 

This will instantiate a servlet in web.xml before the request comes to the server.

If you have this set already in your web.xml and don't see any changes to the problem, try to use a standard .war package for deployment if you're using an exploded version on your dev machine.

Shawn
  • 513
  • 9
  • 18
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
2

While the accepted answer by Crazy Ninja is correct, there is an alternative.

ServletContextListener

The Servlet spec defines the ServletContextListener interface for you to define a class to be instantiated and invoked:

  • Before any of your servlets (and filters) begin executing, and…
  • After the last of your servlets (and filters) have finished executing because your web app is being shutdown.

Your class implementing the ServletContextListener is invoked whenever the web app (the “context”) has been initialized by the Servlet container.

Some Servlet containers automatically initialize their contexts when launched. So your initialization code place here may execute long before your first user hits the server. Whenever your container chooses to initialize your web app (context), rest assured that the Servlet spec guarantees that any container runs, and finishes running, your context listener before handling the first call to your servlets/filters.

I just happened to post a Question/Answer pair on this topic, Hook for my Vaadin web app starting and stopping?. See that page for much more discussion.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154