JSF注入託管bean範例


以下程式碼顯示了如何進行bean注入。
我們先定義一個訊息bean,它有一個字串屬性來儲存訊息。

@ManagedBean(name="message")
@SessionScoped
public class MessageBean implements Serializable {

  private static final long serialVersionUID = 1L;

  private String sayWelcome = "Welcome to JSF 2.0";

然後我們再定義另一個託管bean,並使用@ManagedProperty註解注入MessageBean

@ManagedBean
@SessionScoped
public class UserBean implements Serializable {

  private static final long serialVersionUID = 1L;

  @ManagedProperty(value="#{message}")
  private MessageBean messageBean;

  public void setMessageBean(MessageBean messageBean) {
    this.messageBean = messageBean;
  }

範例

開啟 NetBean8.2,建立一個名為: InjectManagedBeans 的工程,並加入以下檔案程式碼。
以下是檔案:UserBean.java 中的程式碼 -

package com.yiibai;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class UserBean implements Serializable {

  private static final long serialVersionUID = 1L;

  @ManagedProperty(value="#{message}")
  private MessageBean messageBean;

  public void setMessageBean(MessageBean messageBean) {
    this.messageBean = messageBean;
  }

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSayWelcome(){
    //check if null?
    if("".equals(name) || name ==null){
      return "";
    }else{
      return messageBean.getSayWelcome() + name;
    }
  }

}

以下是是檔案:index.xhtml 中的程式碼 -

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">

    <h:body>

      <h:form>
         <h:inputText id="name" value="#{userBean.name}"></h:inputText>
         <h:commandButton value="Welcome Me">
         <f:ajax execute="name" render="output" />
         </h:commandButton>

         <h2><h:outputText id="output" value="#{userBean.sayWelcome}" /></h2>  
      </h:form>

    </h:body>
</html>

以下是檔案:MessageBean.java 中的程式碼 -

package com.yiibai;
import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="message")
@SessionScoped
public class MessageBean implements Serializable {

  private static final long serialVersionUID = 1L;

  private String sayWelcome = "Welcome to JSF 2.0";

  public String getSayWelcome() {
    return sayWelcome;
  }

  public void setSayWelcome(String sayWelcome) {
    this.sayWelcome = sayWelcome;
  }

}

執行測試結果

Tomcat啟動完成後,在瀏覽器位址列中輸入以下URL。

http://localhost:8084/InjectManagedBeans/

執行結果如下所示 -