资源预览内容
第1页 / 共2页
第2页 / 共2页
亲,该文档总共2页全部预览完了,如果喜欢就下载吧!
资源描述
jsf bean 设置与后台访问方法再来解释JSF中的MBean,其实MBean就是一个JavaBean,因此它有着和JavaBean相同的要求。最后是MBean的配置,JSF的MBean需要在faces-config文件中做配置,配置方法如下:12demo of config3userInfo4user5net.moon.beans.UserInfo6session7对其中的managed-bean-name,managed-bean-class和managed-bean-scope做一下解释。managed-bean-name是这一MBean的名字,用于其它位置的调用。managed-bean-class是这一MBean的完整路径,用于指明该MBean的类文件位置。managed-bean-scope是这一MBean的有效范围。下面再对manage-bean-scope进行一下详细的解释,其有效取值为:application, session, request, none。很容易理解,它们的存活周期分别如下:Name ScopeApplication整个应用Session整个对话Request整个请求None需要时,临时大家知道,JSF是以JSP为基础的,那么,对于JSP的九大对象来说,这四种scope的信息到底是怎么存储的呢?经过测试证明,scope为applicatoin的MBean的实例保存在ServletContext中,也就是JSP中的application中,因此我们可以用如下的方法得到某个类的引用:1FacesContext fc = FacesContext.getCurrentInstance();2UserInfo ui = (serInfo)fc.getExternalContext().getApplicationMap().get(user);对session级别的MBean,我们可以用如下方法得到其引用:1FacesContext fc = FacesContext.getCurrentInstance();2UserInfo ub = (UserInfo)fc.getExternalContext().getSessionMap().get(userInfo);当然,我们也可以用其它的方法得到session对象后,从session中取出实例。对request级别的MBean,我们可从request对象中取得,代码如下:1FacesContext fc = FacesContext.getCurrentInstance();2HttpServletRequest request = (HttpServletRequest)fc.getExternalContext().getRequest();3UserInfo ui = (UserInfo)request.getAttribute(user);至于none类型的MBean,应该只能得到新的实例了。当然,JSF提供了另外的访问MBean的方法,我们可以用如下的代码得到MBean的实例:1FacesContext context = FacesContext.getCurrentInstance();2ValueBinding binding = context.getApplication().createValueBinding(#user);3UserBean user = (UserBean) binding.getValue(context);也可用如下的代碼直接得到MBean的一個屬性:1FacesContext context = FacesContext.getCurrentInstance();2ValueBinding binding = context.getApplication().createValueBinding(#user.name);3String name = (String) binding.getValue(context);上面通过ValueBinding获取值的方法在最新版的jsf中已废弃,新版的jsf提供了另一种访问MBean的方法,是通过ELResolver来获取:/用法: getMBean(context, UserNavigation);public static Object getBean(FacesContext context, String beanName)ELResolver elr = context.getApplication().getELResolver();Object value = elr.getValue(context.getELContext(), null, beanName);return value;这种方法的好处是可以和spring结合使用,即在MBean中找不到时去Spring的bean中查找,需要在faces-config.xml中添加以下配置:org.springframework.web.jsf.el.SpringBeanFacesELResolver也有方法可以通过EL表达式来获取Bean,如下:/ evalExpr(context, #UserNavigation.userName);public static Object evalExpr(FacesContext context, String el_expr)return context.getApplication().evaluateExpressionGet(context, el_expr, Object.class);
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号