tags:

views:

91

answers:

1

Is there a way to access JSF managed beans from a servlet?

+2  A: 

In a Servlet, you can get request scoped beans by:

Bean bean = (Bean) request.getAttribute("beanName");

and session scoped beans by:

Bean bean = (Bean) request.getSession().getAttribute("beanName);

and application scoped beans by:

Bean bean = (Bean) getServletContext().getAttribute("beanName");
BalusC
As far as I know beans are not necessarily instantiated eagerly by JSF. So this will fail if beans were not accessed before via the JSF layer.
lexicore
@lexi: That's correct. However, if you need to instantiate those beans in a servlet yourself instead of grabbing the already-created ones, then there's something more wrong in the approach/design. Either the task is to be done fully by a JSF bean, or you don't need JSF at all for the particular task. Hard to say because the OP's actual functional requirement is vague. Remember that a Servlet is basically just a page/front controller, the job the FacesServlet has already fullfilled. Maybe the servlet is doing too much or the OP simply fails to do the same in a JSF bean.
BalusC
@BalusC: I can follow your argumentation but don't agree entirely. One can use JSF for bean management and non-Faces servlets for front-end which does not fit JSF very well. For instance, something like DWR. Me personally, I generally prefer Spring for DI rather than JSF managed beans, but there's a lot of scenarios where JSF would be more than enough for bean management.
lexicore