完成了UIComponent的定制后,下面就需要自定義一個Tag來與之對應。自定義Tag的目的在于設定UIComponent的屬性,取得Renderer的值等。
自定義Tag需要繼承UIComponentTag:
package
test;
import
javax.faces.application.Application;
import
javax.faces.component.UIComponent;
import
javax.faces.context.FacesContext;
import
javax.faces.el.ValueBinding;
import
javax.faces.webapp.UIComponentTag;
public class TextWithCmdTag extends UIComponentTag
{
private String size;
private String value;
public
String getComponentType() {
return "test.TextWithCmd";
}
綁定到Renderer。這里沒有設定,因為這個組件沒有用Renderer編解碼,而是Component自己實現的。
|
|
public
String getRendererType() {
return null;
}
public void setProperties(UIComponent component)
{
super.setProperties(component);
setStringProperty(component,
"size", size);
setStringProperty(component,
"value", value);
}
private void setStringProperty(UIComponent
component,
String attrName, String
attrValue) {
if(attrValue == null)
return;
設置Tag的值綁定到Component上。這樣,Component取值的時候,如果元件屬性設定值找不到,就會從綁定值中去尋找。
|
|
if(isValueReference(attrValue)) {
FacesContext context =
FacesContext.getCurrentInstance();
Application application =
context.getApplication();
ValueBinding binding =
application.createValueBinding(attrValue);
component.setValueBinding(attrName, binding);
}
else {
component.getAttributes().
put(attrName,
attrValue);
}
}
public void release() {
super.release();
size = null;
value = null;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
▲綁定到Tag上的Conponent組件用的是faces-config.xml中定義的別名,所以我們隨時可以替換掉對于的Component而不改變Tag代碼。
自定義Tag需要在Tld中聲明:
<tag>
<name>textcmd</name>
<tag-class>test.TextWithCmdTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>size</name>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
</attribute>
</tag>
具體程序參看示例程序。
新建一個JSP和一個綁定好的javaBean,就可以看到運行結果了。
對這類jsp和Bean的建立,前面已經有很多例子了,這里就不再說了。
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>
<%@ taglib uri="/WEB-INF/textcmd.tld" prefix="oc"%>
<html>
<link href="../../styles.css" rel="stylesheet" type="text/css" />
<head>
<title></title>
</head>
<body>
<f:view>
<h:form>
Input data: <oc:textcmd size="10"
value="#{componentTestBean.data}" />
</h:form>
<h:outputText value="#{componentTestBean.data}" />
</f:view>
</body>
</html>
運行地址:http://localhost:8080/jsfTest/pages/componentTest.faces
具體程序參看示例程序。