通常我们都是在页面里通过EL表达式实现对Managed Bean属性值的读取,Event的处理及函数的调用。然而,某些情况下,我们不得不在程序里直接访问某些Managed Bean,通常有3种处理方法可实现编程式的访问Managed Bean。
1、Managed Bean的依赖注入
JSF2可通过@ManagedProperty Anotation实现testMB对mainMB的注入,如下所示。
@ManagedProperty(value="#{mainMB}")
private MainControllerMB mainMB;
public getter, setter…
到此,我们已经可以在该类中访问mainMB的方法。这里需要注意的是testMB和mainMB的scope,请看下表。
Scope |
Description |
Can Only Reference Other Managed Beans: |
none or @NoneScoped |
Managed beans with a none scope are not instantiated nor stored in any other scope. Instead, they are instantiated on demand by another managed bean. Once created, they will persist as long as the calling bean stays alive because their scope will match the calling bean’s scope. |
none |
request or @RequestScoped |
Managed beans registered with request scope will be instantiated and stay available throughout a single HTTP request. This means that the bean can survive a navigation to another page, provided it was during the same HTTP request. |
none, request, view, session, application |
view or @ViewScoped |
Managed beans registered in view scope remain available as long as the user stays on the same view. Navigating away from that view will cause beans registered in that view’s scope to be deallocated. |
none, view, session, application |
session or @SessionScoped |
Managed beans registered with a session scope will be stored on the HTTP session. This means that the values in the managed bean will persist beyond a single HTTP request for a single user. This is ideal for a shopping cart type of usage where values must be stored and made available during multiple requests. |
none, session, application |
application or @ApplicationScoped |
Managed beans registered with an application scope retain their values throughout the lifetime of the application and are available to all users. |
none, application |
2、Bean查找
可以在testMB中利用facescontext查找mainMB,假设mainMB是sessionscope的,则我们可以通过如下代码查找:
public static AbstractMB findBeanByName(String name) {
return (AbstractMB) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get(name);
}
3、通过ExpressionFactory进行表达式求解
1)属性值读取
ELContext elContext = FacesContext.getCurrentInstance().getELContext( );
Application application = FacesContext.getCurrentInstance().getApplication( );
String userid = (String) application.evaluateValueExpressionGet(context,
"#{userBean.userid}",String.class);
2)方法调用
Application application = FacesContext.getCurrentInstance().getApplication();
ELContext elContext = FacesContext.getCurrentInstance().getELContext( );
ExpressionFactory expressionFactory = application.getExpressionFactory( );
MethodExpression me = expressionFactory.
createMethodExpression(elContext,"#{userBean.addConfirmedUser}",
Void.class, null);
try
{
me.invoke(context, null);
}catch (ELException e){}