JSFJSF用戶界面組件模型
JSF UI組件示例
JSF <h:inputText>標籤
JSF <h:outputText>標籤
JSF <h:form>標籤
JSF <h:commandButton>標籤
JSF <h:inputtextarea>標籤
JSF <h:commandLink>標籤
JSF <h:inputSecret>標籤
JSF <h:inputHidden>標籤
JSF <h:inputFile>標籤
JSF <h:graphicImage>標籤
JSF <h:message>標籤
JSF <f:ajax>標籤
JSF單選按鈕
JSF表單組合框
JSF列表框
JSF多選列表框
JSF輸出格式化
JSF輸出樣式
JSF <h:attribute>標籤
JSF <h:setPropertyActionListener>標籤
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](https://github.com/ManagedProperty "@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/
運行結果如下所示 -