views:

42

answers:

1

Hi

i would like to initialize (in Struts2) a property(data loading from a file) only once and make available that property for entire struts 2 application. how can i achieve that? do i need override struts 2 dispatcher?

Regards Raju

+1  A: 

You could create a ServletContextListener defined in web.xml that opens your property file and sets the desired value to the ServletContext via:

getServletContext().setAttribute("dataKey", dataValue);

The ServletContext has application-wide scope.

Update:

You can create a new class that implements ServletContextListener (here is its JavaDoc: ServletContextListener), which requires that you define contextInitialized() and contextDestroyed() methods.

The method contextInitialized() is called right before your servlet begins accepting requests. In your contextInitialized() method, you would include the getServletContext().setAttribute("dataKey", dataValue) call.

In order to register your listener, you will need to add a listener definition in your web.xml file:

<listener>
    <listener-class>CLASS_PATH.CLASS_NAME</listener-class>
</listener>

You'll need to replace CLASS_PATH.CLASS_NAME in the above XML with the class path and name of the context listener class you just created.

Abboq
thanks for your reply...i am using Struts 2..how do i do that....i have to override struts2 dispatcher right....
raju
I provided more detail instructions on how to implement a ServletContextListener. Please let me know if you have trouble with my directions.
Abboq
thanks for your reply...
raju