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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With