Reputation: 6309
Need to add a Java class (named HistoryBean in my project) to the ServletContext. I do not want to create new instance of the HistoryBean class in the different Servlets that I have inside my project. I want to get it from the ServletContext. Please help me with suggestions.
Upvotes: 0
Views: 310
Reputation: 1109292
As you're using JSF, just register it as an application scoped bean.
@ManagedBean(eager=true)
@ApplicationScoped
public class HistoryBean {
// ...
}
(note the eager=true
, this autoconstructs the bean on webapp's startup without the need to reference it in some view or bean, you don't need a ServletContextListener
for this)
This way it's not only available in JSF context the usual way as #{historyBean}
, but it's in servlets also available as a servlet context attribute with the managed bean name as key as follows:
HistoryBean historyBean = (HistoryBean) getServletContext().getAttribute("historyBean");
Upvotes: 3
Reputation: 597264
You can do that in a ServletContextListener
:
public void contextInitialized(ServletContextEvent e) {
e.getServletContext().setAttribute("historyBean", new HistoryBean());
}
Register your listener with @WebListener
or with <listener>..</listener>
in web.xml.
Upvotes: 3