I have to execute a struts2 action on server startup rather than on the first request.
问题:
回答1:
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
).
Action
s are invoked by Request
s coming from the Client
s (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...).
回答2:
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
回答3:
If you want to some code to run when your web application, aka Servlet Context, starts for the first time, then you should leverage the hooks provided by the technology. The Servlet API provides lifecycle hooks for you to use to fire code at various lifecycle stages of a web application. Since all Struts 2 applications are Servlet API web applications, then you can leverage this yourself.
The ServletContextListener interface provides an init hook method. You simply implement this interface and register your implementation in the web.xml.
Note, if what you need to do is more Struts 2 specific, then you could consider utilizing something from within the Struts 2 API itself.
回答4:
Load on start-up in servlet and jsp is present as below
You can ask the page to be loaded when the server starts. This is done via the web.xml
file
<servlet>
<servlet-name>login</servlet-name>
<jsp-file>/login.jsp</jsp-file>
<load-on-startup>1</load-on-startup>
</servlet>
Normally jsp file is compiles on first hit. Now the code says precompile a jsp file without waiting for the first hit.
For struts2 you can change programatically in web.xml
<listener>
<listener-class>your listener class</listener-class>
</listener>
refer this link it might be helpful to you
Loadonstart up.