JSF教程 - JSF管理Bean
JSF教程 - JSF管理Bean
JSF Managed Bean是使用JSF注册的常规Java Bean类。
JSF Managed Bean是使用JSF注册的常规Java Bean类。...
JSF管理的bean作为UI组件的模型。 它存储使用的数据通过JSF xhtml页面。
在JSF框架的帮助下,Managed Bean可以从JSF页面访问。
在JSF 1.2中,我们必须在JSF配置文件中注册一个托管bean例如faces-config.xml。
从JSF 2.0,可以使用注释注册托管bean。
使用XML配置
以下代码显示如何注册JSF受管Bean
<managed-bean> <managed-bean-name>helloWorld</managed-bean-name> <managed-bean-class>com.w3cschool.test.HelloWorld</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>message</managed-bean-name> <managed-bean-class>com.w3cschool.test.Message</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>
使用@ManagedBean注释
以下代码显示了如何使用注释注册JSF受管Bean。
@ManagedBean(name = "helloWorld", eager = true) @RequestScoped public class HelloWorld { @ManagedProperty(value="#{message}") private Message message; ... }
@ManagedBean
将bean标记为在name属性中指定的名称的托管bean。
如果未指定name属性,则指定受管bean名称将默认为简单类名称,第一个字母为lowercased。 在我们的情况下,它会是helloWorld。
如果eager设置为“true",那么在请求bean之前创建managed bean。
“lazy"初始化被使用在bean将被创建只有当它被请求。
使用@ManagedBean注释...
范围注释设置受管bean的范围。
如果未指定scope,那么bean将默认为请求作用域。
我们可以将JSF bean范围设置为以下列表。
-
@RequestScoped
bean lives as long as the HTTP request-response lives. It get created upon a HTTP request and get destroyed when the HTTP response associated with the HTTP request is finished. -
@NoneScoped
bean stays as long as a single Expression Language(EL) evaluation. It get created upon an EL evaluation and get destroyed after the EL evaluation. -
@ViewScoped
bean lives as long as user is interacting with the same JSF view in the browser window. It gets created upon a HTTP request and gets destroyed when users navigate to a different view. - @SessionScoped bean lives as long as the HTTP session lives. It gets created upon the first HTTP request and gets destroyed when the HTTP session is invalidated.
- @ApplicationScoped bean lives as long as the web application lives. It gets created upon the first HTTP request or when the web application starts up and the eager=true attribute is set in @ManagedBean and gets destroyed when the web application shuts down.
- @CustomScoped bean lives as long as the bean"s entry in the custom Map which is created for this scope lives.
@ManagedProperty注释
JSF是一个简单的静态依赖注入(DI)框架。@ManagedProperty注释标记要注入到另一个托管bean中的托管bean的属性。
更多建议: