@WebServlet在基于 servlet 的工件中,例如@WebFilter和@WebListener,您可以通过以下方式获取“普通版”JSF @ManagedBean @RequestScoped:
Bean bean = (Bean) request.getAttribute("beanName");
并@ManagedBean @SessionScoped通过:
Bean bean = (Bean) request.getSession().getAttribute("beanName");
并@ManagedBean @ApplicationScoped通过:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
请注意,这预先要求 bean 已经由 JSF 预先自动创建。否则这些将返回null。然后,您需要手动创建 bean 并使用setAttribute("beanName", bean).
如果您能够使用 CDI@Named而不是自 JSF 2.3 deprecated 以来的版本@ManagedBean,那么它会更加容易,特别是因为您不再需要手动创建 bean:
@Inject
private Bean bean;
请注意,这在您使用时不起作用,@Named @ViewScoped因为 bean 只能由 JSF 视图状态标识,并且只有在FacesServlet被调用时才可用。因此,在之前运行的过滤器中,访问@Injected@ViewScoped总是会抛出ContextNotActiveException.
只有当你在里面时@ManagedBean,你才能使用@ManagedProperty:
@ManagedProperty("#{bean}")
private Bean bean;
@Named请注意,这在 a or@WebServlet或任何其他工件内不起作用。它真的@ManagedBean只在里面有效。
如果您不在 a 内@ManagedBean,但aFacesContext随时可用(即FacesContext#getCurrentInstance()不返回null),您也可以使用Application#evaluateExpressionGet():
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
这可以方便如下:
@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
并可按如下方式使用:
Bean bean = findBean("bean");
也可以看看: