可以将@ManagedBean作为@ManagedProperty注入@WebServlet吗? [英] Possible to inject @ManagedBean as a @ManagedProperty into @WebServlet?

查看:113
本文介绍了可以将@ManagedBean作为@ManagedProperty注入@WebServlet吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java EE 6-webapp(运行在最新的GlassFish 3.1上)中,我使用JSF2-ManagedBeans和 @ManagedProperty 将它们注入其他ManagedBeans。现在我想知道我是否也可以使用<$ c $将 @ManagedBean 注入 @WebServlet C> @ManagedProperty 。一些代码:

In my Java EE 6-webapp (running on latest GlassFish 3.1), I'm using JSF2-ManagedBeans and @ManagedProperty to inject them into other ManagedBeans. Now i would like to know if i can also inject a @ManagedBean into a @WebServlet, using @ManagedProperty. Some code:

@WebServlet(name = "vdd")
public class VddServlet extends HttpServlet
{
  @ManagedProperty(value = "#{userIdentity}")
  private UserIdentity identity;
}

ManagedBean如下所示:

The ManagedBean looks like this:

@ManagedBean
public class UserIdentity 
{
  ...
}

它是否有效?如果没有,我有什么其他方法将ManagedBean注入WebServlet(没有CDI,目前不是一个选项 - 因为GF 3.1 B32 / 33与OSGi-Java EE-apps结合存在一些问题,但我们时间很短)?

Does it work like this? If not, what other ways do i have to inject a ManagedBean into a WebServlet (without CDI, which is currently not an option - since there are some issues in GF 3.1 B32/33 in combination with OSGi-Java EE-apps, but we are short on time)?

推荐答案

在servlet中使用 @ManagedProperty 是不可能的,因为这只适用于 @ManagedBean 类。此外,注入一个范围小于父本身的对象也是不可能的,因为这也只会导致并发问题。注入器会为此抛出一个runtimeexception。 servlet本质上是应用程序范围并在所有用户之间共享,并且您的 UserIdentity bean似乎是会话作用域。

Using @ManagedProperty in a servlet is not possible since this works in @ManagedBean classes only. Further, injecting an object which has a lesser scope than the parent itself is also not possible since that would also only end up in concurrency problems. The injector would throw a runtimeexception for that. A servlet is in essence application scoped and shared among all users and your UserIdentity bean seems to be session scoped.

由于JSF在Servlet API之上运行并将会话范围的bean存储在会话中,因此您可以在servlet中将其作为会话属性获取: / p>

Since JSF runs on top of the Servlet API and stores the session scoped beans in, well, the session, you could in the servlet just grab it as session attribute:

UserIdentity identity = (UserIdentity) request.getSession().getAttribute("userIdentity");

请注意 FacesContext 通常也不是在 FacesServlet 以外的servlet中可用,所以在评论中建议的servlet中使用 FacesContext 没有任何意义,这只会返回 null

Note that the FacesContext is usually also not available in a servlet other than FacesServlet, so using FacesContext in the servlet as suggested in a comment does not make any sense, that would only return null.

这篇关于可以将@ManagedBean作为@ManagedProperty注入@WebServlet吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆