2011年11月20日星期日

JavaEE_015:JavaEE6 新特性之五:JSF 2.0(2)

3. 复合组件
复合组件可以把多个JSF组件组合起来形成一个新的组件,放到共享库中后,可以供其它页面使用。
复合组件也可以有验证器,转换器和监听器,这一点和标准JSF组件一样。
下面是复合组件的定义:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name="item" required="true"/>
</composite:interface>

<composite:implementation>

<h:panelGrid columns="2">
<h:outputLabel value="Title : " styleClass="alabel" />
<h:inputText value="#{cc.attrs.item.title}" styleClass="ainput"/>

<h:outputLabel value="Price : " styleClass="alabel"/>
<h:inputText value="#{cc.attrs.item.price}" styleClass="ainput"/>

<h:outputLabel value="Description : " styleClass="alabel"/>
<h:inputTextarea value="#{cc.attrs.item.description}" styleClass="atextarea"/>
</h:panelGrid>

</composite:implementation>
</html>

可以看出,xmlns:composite="http://java.sun.com/jsf/composite"声明了复合组件的命名空间。
<composite:interface>标签声明复合组件的使用契约,
<composite:attribute>标签在契约中使用<composite:attribute>标签表示一个属性:item对象。
<composite:implementation>标签定义了复合组件的实现,访问item对象的属性,并用InputText和InputTextarea组合实现。
如果想在契约中指定某个事件,可以使用<composite:actionSource>标签。
<composite:interface>
<composite:actionSource name="loginEvent"/>
</composite:interface>
对应的实现方法代码如下:
<ez:loginPanel>
<f:actionListener for="loginEvent" type="example01.LoginActionListener" />
</ez:loginPanel>
对应的ActionListener代码如下:
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

public class LoginActionListener implements ActionListener {
public void processAction(ActionEvent event) throws AbortProcessingException {
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getRequestMap().put("loginActionMessage", "Login event happened");
}
}
下面是复合组件实现的片段代码:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:demo="http://java.sun.com/jsf/composite/components">

<ui:composition template="layout.xhtml">

<ui:define name="title">Create a new book</ui:define>

<ui:define name="content">

<h:form style="background-image:url(#{resource['book.png']});">
<demo:newItem item="#{itemBean.book}"/>
.....
可以看出,这里使用了xmlns:demo命名空间,该命名空间最终指向"components";使用demo:newItem索引该组合对象。
这表明在应用程序根目录下的resources目录(resources目录是保留目录)下有一个子目录:components。
在components目录下,有一个名称为newItem.xhtml的文件。
JSF运行时,会根据“复合组件的标签名.xhtml”查找复合组件。

没有评论: