`

Jsf Mbean Scope

    博客分类:
  • Jsf
阅读更多

JSF中的MBean,其实MBean就是一个JavaBean,因此它有着和JavaBean相同的要求。 最后是MBean的配置,JSF的MBean需要在faces-config文件中做配置,配置方法如下:

 <managed-bean>

<description>demo of config</description>

 <display-name>userInfo</display-name>

<managed-bean-name>user</managed-bean-name>

 <managed-bean-class>net.moon.beans.UserInfo</managed-bean-class>

 <managed-bean-scope>session</managed-bean-scope> </managed-bean>

 

下面再对manage-bean-scope进行一下详细的解释,其有效取值为:application, session, request, none。很容易理解,它们的存活周期分别如下:

 Name Scope

Application 整个应用

Session 整个对话

Request 整个请求

 None 需要时,临时

大家知道,JSF是以JSP为基础的,那么,对于JSP的九大对象来说,这四种scope的信息到底是怎么存储的呢?经过测试证明,scope为applicatoin的MBean的实例保存在ServletContext中,也就是JSP中的application中,因此我们可以用如下的方法得到某个类的引用:

FacesContext fc = FacesContext.getCurrentInstance();

UserInfo ui = (serInfo)fc.getExternalContext().getApplicationMap().get("user");

 

对session级别的MBean,我们可以用如下方法得到其引用:

FacesContext fc = FacesContext.getCurrentInstance();

UserInfo ub = (UserInfo)fc.getExternalContext().getSessionMap().get("userInfo");

当然,我们也可以用其它的方法得到session对象后,从session中取出实例。 对request级别的MBean,我们可从request对象中取得,代码如下:

 FacesContext fc = FacesContext.getCurrentInstance();

HttpServletRequest request = (HttpServletRequest)fc.getExternalContext().getRequest();

 UserInfo ui = (UserInfo)request.getAttribute("user");

 

至于none类型的MBean,应该只能得到新的实例了。

 当然,JSF提供了另外的访问MBean的方法,我们可以用如下的代码得到MBean的实例:

 FacesContext context = FacesContext.getCurrentInstance();

ValueBinding binding = context.getApplication().createValueBinding("#{user}");

UserBean user = (UserBean) binding.getValue(context);

 

也可用如下的代碼直接得到MBean的一個屬性:

 FacesContext context = FacesContext.getCurrentInstance();

 ValueBinding binding = context.getApplication().createValueBinding("#{user.name}");

String name = (String) binding.getValue(context);

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics