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

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

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...).

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

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.

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.

Related

Jersey initialization code after webapp is fully started

I asked this question earlier:
Jersey app-run initialization code on startup to initialize application
Is there any way to run this initialization code after the server has initialized the web app fully ? I am running into a catch-22 problem in that I need the web app fully started by Tomcat before I can run my login call once ?
There are a few considerations. First, Jersey is implemented as a servlet, and that's how it gets loaded. The simplest way to decouple servlet startup from servlet context startup is to not load it on startup. Accomplish this by omitting the load-on-startup element from the servlet descriptor in the web.xml. Setting it to a non-positive should also work.
If you must load the servlet on startup but still want to decouple it, which was my case, you'll probably have to write some custom code, which I did. I couldn't think of any other way. Use a listener of some type--a ServletContextListener or Spring ApplicationListener, depending on exactly how your app is set up--to kick off a new thread that will initialize your Jersey servlet by making an HTTP request to it. It feels a little dirty, but like I said, it's the only thing I and my team could come up with.

How to configure Permanent Servlets in Tomcat 6?

Permanent servlets are loaded when the server is started, and live until the server is
shutdown.
I have requirement to start some server side java programs and These programs then provide functionality that is totally unique and independent of the web server. I wish to do it on Tomcat startup. Solution I see is Permanent Servlet, Which will invokes these Java programs.
So How to configure Permanent Servlets in Tomcat 6 ?
More Details about Permanent Servlets from http://java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html
Temporary versus Permanent Servlets
Servlets can be started and stopped for each client request, or they can be started as the web server is started and kept alive until the server is shut down. Temporary servlets are loaded on demand and offer a good way to conserve resources in the server for less-used functions.
Permanent servlets are loaded when the server is started, and live until the server is shutdown. Servlets are installed as permanent extensions to a server when their start-up costs are very high (such as establishing a connection with a DBMS), when they offer permanent server-side functionality (such as an RMI service), or when they must respond as fast as possible to client requests.
There is no special code necessary to make a servlet temporary or permanent; this is a function of the server configuration.
Because servlets can be loaded when a web server starts, they can use this auto-loading mechanism to provide easier loading of server-side Java programs. These programs can then provide functionality that is totally unique and independent of the web server. For example, a servlet could provide R-based services (rlogin, rsh, ...) through TCP/IP ports while using the servlet request/response protocol to present and process HTML pages used to manage the servlet.
You can do what you need with a ServletContextListener. Register one in your web.xml, e.g.:
<listener>
<listener-class>com.example.MyServletContextListener</listener-class>
</listener>
Then create that class to do what you want:
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
// initialize and startup whatever you need here
}
public void contextDestroyed(ServletContextEvent sce) {
// shutdown and destroy those things here
}
}
I think what they are referring to when they say "permanent servlets" are just the servlets you define in the web.xml, a la,
<servlet>
<description>I'm permanent</description>
<display-name>Servlet</display-name>
<servlet-name>Servlet</servlet-name>
<servlet-class>com.servlet.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
This servlet will be started up when the server starts and will be kept around until it shuts down, probably (See below).
An example temporary servlet would be a .jsp file. It wont load the file up until it is requested and it will probably dispose of it after servicing the request.
Looking at the Servlet Specification about servlet lifecycles,
When the servlet engine is started, needed servlet classes must be located by the
servlet container. The servlet container loads the servlet class using normal Java class
loading facilities. ...
After loading the Servlet class, the container instantiates it for use.
Then for eol,
The servlet container is not required to keep a servlet loaded for any particular
period of time. A servlet instance may be kept active in a servlet container for a
period of milliseconds, for the lifetime of the servlet container (which could be a
number of days, months, or years), or any amount of time in between.
When the servlet container determines that a servlet should be removed from
service, it calls the destroy method of the Servlet interface to allow the servlet to
release any resources it is using and save any persistent state. For example, the
container may do this when it wants to conserve memory resources, or when it is
being shut down.
Before the servlet container calls the destroy method, it must allow any threads that
are currently running in the service method of the servlet to complete execution, or
exceed a server-defined time limit.
Once the destroy method is called on a servlet instance, the container may not route
other requests to that instance of the servlet. If the container needs to enable the
servlet again, it must do so with a new instance of the servlet’s class.
After the destroy method completes, the servlet container must release the servlet
instance so that it is eligible for garbage collection.
So I think bottom line, the servlet specification makes no guarantee as to how long a servlet will be kept, it is implementation specific, but I think its a pretty safe bet that if you load it on start up it will remain loaded for the whole time the server is running.
For your specific use case though, follow WhiteFang34, as using a servlet for something other than servicing requests is abusing the API IMO.
[Edit] Everywhere I look to see how a servlets' lifecycle is managed seems to say that it will remain loaded for the entirety of the webapps lifetime.
Servlets
What is the difference between JSF, Servlet and JSP?
java servlet instantiation and session variables
But nowhere can I find a reference that says that, so I just don't know for certain.

Exact Meaning of Struts Interceptor

Can anyone tell me, what is exact meaning of INTERCEPTOR in Struts 2 Framework?
Could you please give me some simple example with Struts interceptor?
Thanks IN Advance!
Think of what the Interceptors is to Struts as Filters is to Servlets. When you request a Struts Action, The Struts Framework sends a request to the called action, but before the action is executed, the invocation can be interpreted by interceptors. Once the're done, the request is passed (as servlet calls it, filtered) to the action.
The reason for interceptors is, you want to do some pre-conditional / post-conditional checking to be sent to the action / returned by the action. A simple example will be File upload. When you send a file to an action in Struts, you can have an interceptor that is used as a pre-condition validator (e.g, the file size must be 5210 bytes exactly = 5MB). If successful, it filters the request to the action (that was called).
I've never used Struts 2 but there's a Wiki on Interceptors at Apache site.
Well Why Interceptors or whats there relevancy in Struts2..These are a part of moduler approach where you have some predefined modules as per the need and you can plug them or unplug them as per your need.
Struts2 is a web frame work and in order to process the request it has to undergo certain steps which are common for every request process cycle so Struts2 develoers have created these module which are indentiifed as common module which every request in web application needs
like when you submit the data we need to conver the data to appropriate form this is struts is being done by the Interceptors if some validation is needed how to do it is being done by interceptors they are somethig which are like modules or plugin plug which ever you want to use and unplug them which you don't do..
in shorter terem these Interceptors is doing all necessary work for you so that you can concentrate on ur business logic

initialize ServletContext using a method on a Resin server

Is there a way to initialize the ServletContext for a webapp on a Resin server using a method? I need something like that runs once, when the server starts up.
You need to use a ServletContextListener.
http://www.java-tips.org/java-ee-tips/java-servlet/how-to-work-with-servletcontextlistener.html
This J2EE tip demonstrates use of
ServletContextListener. This event
class handles notifications about
changes to the servlet context of the
Web application that they are part of.
This can be explained as if someone is
present on the server and dynamically
informing us about the events that are
occuring on the server. There acquire
need of Listners. Therefore,
ServletContextListner is helpful in
informing about context Initilazation
and destruction.
Use the <load-on-startup/> in the <servlet> tag.

Java, NetBean : Access web.xml context parameters from Web Service method?

I am new to java so excuse my lame questions:)
I am trying to build a web service in Java NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net).
What is the right way to save and access such settings in a java web service.
Is there a way to read context parameters from web.xml in a web method?
If no what are the alternatives for storing your configuration variables like pathnames ?
Thank you
Is there a way to read context parameters from web.xml in a web method?
No, this is not easily done using the out-of-the-box. The Web Service system (JAX-WS) has minimal awareness of the Servlet engine (Tomcat). They are designed to be isolated.
If you wanted to use the context parameters, your web service class would need to implement ServletContextListener and retrieve the desired parameters in the initialization parameter (or save the context for later use). Since the Servlet engine and JAX-WS would each have different instances of the object, you'd need to save the values to a static member.
As Lars mentioned, the Properties API or JNDI are your best bets as they're included with Java and are fairly well-known ways to retrieve options. Use Classloader.getResource() to retrieve the Properties in a web context.
If you are using servlets, you can configure parameters in web.xml:
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
</servlet>
These properties will be passed in a ServletConfig object to your servlet's "init" method.
Another way is to read your system's environment variables with
System.getProperty(String name);
But this is not recommended for other than small programs and tests.
There is also the Properties API if you want to use ".properties" files.
http://java.sun.com/javase/6/docs/api/java/util/Properties.html
Finally, I believe looking up configurations with JNDI is pretty common when developing modern web service applications, Netbeans and app containers have pretty good support for that. Google it.
MessageContext ctx = MessageContext.getCurrentThreadsContext();
Servlet wsServlet = (Servlet) ctx.getProperty(HTTPConstants.MC_HTTP_SERVLET);
ServletConfig wsServletConfig = wsServlet.getServletConfig();
ServletContext wsContext = wsServletConfig.getServletContext();
I think the correct answer is ... as always ... "It depends". If you are just running a small implementation with a single server then it depend much on the WS technology you want to use. Some make the servlet context and the context-params easy to access, others don't, in which case accessing properties from a properties file may be easier. Are you going to have an array of servers in a load balanced environment with high traffic where updating the setting for all servers must be instant and centralized in-case of fail-over? If that's the case then do you really want to update the config files for all servers in the farm? How do you synchronize those changes to all those servers? Does it matter to you? If you're storing path-names in a config file then you probably intend to be able to update the path-names to another host in case certain host goes down ("\file_server_host\doc_store" --> "\backup_file_server_host\doc_store") in which case is may actually be better to fail-over using DNS instead. There are too many variables. It really depends on the design; needs; scale of the app.
For simplicity sake, if you just want a simple equivalent of a .settings file then you want a .properties file. Here is an example where I have recently used this in a project: https://github.com/sylnsr/docx4j-ws/blob/master/src/docx4j/TextSubstitution.java

Categories

Resources