Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Faces ServletContext object inside ManagedBean class

Tags:

servlets

jsf-2

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?

like image 818
Jazib Avatar asked Jan 09 '13 20:01

Jazib


1 Answers

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
like image 50
BalusC Avatar answered Nov 12 '22 03:11

BalusC