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
or PortletContext
) as the one returned when calling getContext()
on the ExternalContext
returned by the FacesContext
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