JSF教程 - JSF管理Bean

2018-01-09 19:01 更新

JSF教程 - JSF管理Bean


JSF Managed Bean是使用JSF注冊(cè)的常規(guī)Java Bean類。

JSF Managed Bean是使用JSF注冊(cè)的常規(guī)Java Bean類。...

JSF管理的bean作為UI組件的模型。 它存儲(chǔ)使用的數(shù)據(jù)通過JSF xhtml頁面。

在JSF框架的幫助下,Managed Bean可以從JSF頁面訪問。

在JSF 1.2中,我們必須在JSF配置文件中注冊(cè)一個(gè)托管bean例如faces-config.xml。

從JSF 2.0,可以使用注釋注冊(cè)托管bean。

使用XML配置

以下代碼顯示如何注冊(cè)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注釋

以下代碼顯示了如何使用注釋注冊(cè)JSF受管Bean。

@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
  
   @ManagedProperty(value="#{message}")
   private Message message;
   ...
}

@ManagedBean 將bean標(biāo)記為在name屬性中指定的名稱的托管bean。

如果未指定name屬性,則指定受管bean名稱將默認(rèn)為簡(jiǎn)單類名稱,第一個(gè)字母為lowercased。 在我們的情況下,它會(huì)是helloWorld。

如果eager設(shè)置為“true",那么在請(qǐng)求bean之前創(chuàng)建managed bean。

“l(fā)azy"初始化被使用在bean將被創(chuàng)建只有當(dāng)它被請(qǐng)求。



使用@ManagedBean注釋...

范圍注釋設(shè)置受管bean的范圍。

如果未指定scope,那么bean將默認(rèn)為請(qǐng)求作用域。

我們可以將JSF bean范圍設(shè)置為以下列表。

  • @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是一個(gè)簡(jiǎn)單的靜態(tài)依賴注入(DI)框架。@ManagedProperty注釋標(biāo)記要注入到另一個(gè)托管bean中的托管bean的屬性。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)