在Component與Tag自訂完成後,這邊來看看如何使用它們,首先定義faces-config.xml:
- faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems,
Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<component>
<component-type>
onlyfun.caterpillar.TextWithCmd
</component-type>
<component-class>
onlyfun.caterpillar.UITextWithCmd
</component-class>
</component>
<managed-bean>
<managed-bean-name>someBean</managed-bean-name>
<managed-bean-class>
onlyfun.caterpillar.SomeBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
<component>中定義Component的型態與實際的類別對應,在您於自訂Tag中呼叫 getComponentType()方法所返回的值,就是尋找<component-type>設定的值對應,並由此得知真正對應的 Component類別。
我們所撰寫的SomeBean測試類別如下:
- SomeBean.java
package onlyfun.caterpillar;
public class SomeBean {
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
這邊寫一個簡單的網頁來測試一下我們撰寫的自訂元件:
- index.jsp
<%@ 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="#{someBean.data}"/>
</h:form>
<h:outputText value="#{someBean.data}"/>
</f:view>
</body>
</html>