tags:

views:

145

answers:

1
+3  A: 

JSF stores application scoped managed beans just in the ServletContext. In servlets, the ServletContext is just available by the inherited getServletContext() method. You don't need to manually create a whole FacesContext around it. That's only an unnecessarily expensive task for this purpose.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Bean bean = (Bean) getServletContext().getAttribute("bean");
    // ...
}

If it returns null, then it simply means that JSF hasn't kicked in yet to auto-create the bean for you (i.e. the servlet is called too early). You would then need to create and store it yourself. It will be used by JSF if the managed bean name (the attribute key) is the same.

    if (bean == null) {
        bean = new Bean();
        getServletContext().setAttribute("bean", bean);
    }

That said, what's the purpose of this servlet? Aren't you trying to achieve some functional requirement the wrong way?

BalusC
OK, now I see where the problem is. I have a managedBean which has a method that creates the bean that I need, but when I get to the servlet, it's not in the ServletContext, because it was never really loaded on it.The purpose of the servlet is to write a file with OutputStream so my user will be able to save the result of a webservice invocation (a PDF file).I know it's not the best approach, but I'm facing a deadline hereAny help is appreciated
azathoth
You can also do this in a managed bean method. You can find some hints in [this answer](http://stackoverflow.com/questions/2914025/forcing-a-save-as-dialogue-from-any-web-browser-from-jsf-application). You should certainly not use the servletcontext for it. It's been **shared** among all users who are using the webapplication.
BalusC
Thank you, with the example you provided I've modified my application, now it's using the same bean (session-scoped) for uploading and downloading, not needing to mess with ServletContext at all.
azathoth
You're welcome.
BalusC