Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run an action on server startup using Struts2?

I have to execute a struts2 action on server startup rather than on the first request.

like image 296
LNyarla Avatar asked Jan 16 '13 12:01

LNyarla


2 Answers

Loading data on startup of an application is a common task, you will find several examples on the web. As said in other answers, you should implement a ServletContextListener (that is not Struts2 specific)... you can read a great example here.

The important thing here is understanding the Action concept:

In Struts2 MVC (Model View Controller) Framework, an Action is the Controller (and part of the Model).

Actions are invoked by Requests coming from the Clients (and one Action is created on every request, so they're thread-safe).

This means that you need a Client, that usually means a guy in front of a pc, clicking on a browser... then, a client call is not the right trigger to perform automated, server-side operation on shared objects.

Of course you could implement some form of lazy-initialitazion (eg. with the help of a custom Interceptor) so that the first user would set-up something in the Application scope, and the other users would retrieve the object already populated, but this is not the best way to do it (you should handle the concurrency on the initialitaion, and you would have one user, the first, waiting for operations that the server could have done in the night on startup...).

like image 77
Andrea Ligios Avatar answered Sep 24 '22 17:09

Andrea Ligios


Write a ServletContextListener, this will be available only one per web application and will get instatiated when the application is deployed.

Here is the post

like image 23
shazin Avatar answered Sep 23 '22 17:09

shazin