Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set some database values to application scope at startup in struts2?

I want to set some values at application scope.

I tried it by using interceptors init() method. But it gives null pointer at below code:

ServletActionContext.getContext().getApplication().put("ApplicationName", applName);

Want access to this field in all sessions.

like image 884
Kidaaaa Avatar asked Jan 14 '23 12:01

Kidaaaa


2 Answers

The canonical way to initialize data on app startup is to use a ServletContextListener.

IMO an interceptor makes little sense for this: interceptors are meant to implement behavior across an application, during the request process, not one-shot functionality at startup.

like image 132
Dave Newton Avatar answered Jan 17 '23 01:01

Dave Newton


You can do it like this:

public class ContextListenerOne implements ServletContextListener {

    ServletContext context;

    @Override
    public void contextInitialized(ServletContextEvent sce) {


        context = sce.getServletContext();

        try {
            //Create a database connection here and run queries to retrieve data.             
            context.setAttribute("data", data); //Use setAttribute method to make this data available to everyone.
        } catch(Exception e {

        }
    }

}

Note that you can also do it by the following unconventional method which is not recommended.

Since only one instance of a Servlet object is created throughout, you can override the init method like this:

@Override
public void init(ServletConfig config) throws ServletException {
    super.init();
    //Do all your database transactions here.
    ServletContext c = config.getServletContext(); //Get the ServletContext.
    c.setAttribute("data", data); //Make data available to all.
}

The init method is only called once no matter how many requests are made during the life cycle of the servlet.

However, note that if you override the init method of a particular type of Servlet, your database data won't be available if a request to another Servlet (not of the type for which you overrode the init method) was made before the very first request to the Servlet for which you overrode the init method.

like image 21
Rafay Avatar answered Jan 17 '23 00:01

Rafay