How to start an action when starting a server using Struts2?

I need to execute the struts2 action when the server starts, and not in the first request.

+6
source share
4 answers

Downloading data at application startup is a common task; you will find several examples on the Internet. As other answers say, you should implement a ServletContextListener (which is not specific to Struts2) ... you can read a great example here .

It is important to understand the concept of action:

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

Action is called by Request , coming from Client (and one action is created for each request, therefore they are thread safe).

This means that you need a client, which usually means a guy in front of a computer, clicking on a browser ... then a client call is not the right trigger for performing an automated server operation on shared objects.

Of course, you could implement some form of lazy-initialitazion (for example, using a custom Interceptor) so that the first user can configure something in the application area, and other users can get an already filled object, but this is not the best way to do this ( you have to handle concurrency in initialization, and you will have one user, the first one, waiting for operations that the server could do at night at startup ...).

+4
source

Write ServletContextListener, this will be available only for each web application and will be installed when the application is deployed.

Here is the message

+2
source

Loading at startup in the servlet and jsp is present below

You can request a page load at server startup. This is done using the web.xml

 <servlet> <servlet-name>login</servlet-name> <jsp-file>/login.jsp</jsp-file> <load-on-startup>1</load-on-startup> </servlet> 

Usually the jsp file compiles on the first hit. Now the code says to precompile the 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> 

link to this link, it may be useful for you

Loadonstart up .

+1
source

If you want some code to run when your web application, for example, the servlet context, is launched for the first time, you must use the hooks provided by the technology. The Servlet API provides lifecycle bindings that you can use to protect code at different stages of the life cycle of a web application. Since all Struts 2 applications are Servlet API web applications, you can use this yourself.

The ServletContextListener interface provides an initialization hook method. You simply implement this interface and register your implementation in web.xml.

Please note that if you need to do more than Struts 2, then you might consider using something from the Struts 2 API itself.

+1
source

All Articles