完成了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;
继承了UIComponentTag。public class TextWithCmdTag extends UIComponentTag
{
private String size;
private String value;
绑定到自定义的Component组件。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中声明:
textcmd
test.TextWithCmdTag
empty
size
value
true
具体程序参看示例程序。
新建一个JSP和一个绑定好的javaBean,就可以看到运行结果了。
对这类jsp和Bean的建立,前面已经有很多例子了,这里就不再说了。
Input data:
具体程序参看示例程序。