syntax_highlight

среда, 6 июня 2012 г.

Access JSF ManagedBean from Servlet

Before giving a ready solution I want to clarify some moments that can answer many unasked questions:
  • FacesContext is ThreadLocal (but ServletContext is not), that's why you can access it in a static way
  • FacesContext cannot be accessed in a static way from a servlet (only if it's FacesServlet)
  • FacesContext store it's beans into request attributes, session attributes or application attributes
  • You cannot inject @ManagedBean as @ManagedProperty into servlet
Now the answer is simple - JSF beans (if they are already instantiated and managed) can be accessed via attributes
JSF bean:
@ManagedBean(name="SimpleBBean")
@SessionScoped
public class SimpleBBean {
  // managed bean properties
}
and in the servlet:
SimpleBBean simpleBBean = (SimpleBBean) this.getServletContext().getAttribute("SimpleBBean");
SimpleBBean simpleBBean2 = (SimpleBBean) request.getAttribute("SimpleBBean");
SimpleBBean simpleBBean3 = (SimpleBBean) request.getSession().getAttribute("SimpleBBean");
response.getWriter().println("beans: " + simpleBBean + " " + simpleBBean2 + " " + simpleBBean3);
the output will be:
beans: null null SimpleBBean@ebf121
you can also set the scope attributes and then retrieve them from FacesContext

Комментариев нет:

Отправить комментарий