I just started learning JSF.
While working with an example, I felt the need to access the ServletContext object inside MyBean class. I wanted to use an object which I had put inside the ServletContext using Listener. Can I do that? Does ServletContext has its scope inside Beans as well?
It's just available by ExternalContext#getContext()
. See also its javadoc:
getContext
public abstract java.lang.Object getContext()
Return the application environment object instance for the current appication.
It is valid to call this method during application startup or shutdown. If called during application startup or shutdown, this returns the same container context instance (
ServletContext
orPortletContext
) as the one returned when callinggetContext()
on theExternalContext
returned by theFacesContext
during an actual request.Servlet: This must be the current application's
javax.servlet.ServletContext
instance.
So, this should do:
public void someMethod() {
ServletContext servletContext = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
// ...
}
Unrelated to the concrete question, depending on the concrete functional requirement, this may not be the right solution to the concrete problem. General consensus is that your JSF code should be as much as possible free of any javax.servlet.*
dependencies/imports. Your question isn't exactly clear, but if you indeed intend to access an attribute which you've put in the servlet context, then just get it from ExternalContext#getApplicationMap()
instead.
E.g. in the ServletContextListener
:
event.getServletContext().setAttribute("foo", foo);
and then in JSF
Foo foo = (Foo) FacesContext.getCurrentInstance().getExternalContext()
.getApplicationMap().get("foo");
or even just by @ManagedProperty
@ManagedProperty("#{foo}")
private Foo foo; // +setter
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