我記得好像是Appfuse的作者曾經這樣評價過Tapestry:只要你真正掌握了Tapestry,你的開發效率將會得到極大的提高。為什么呢?我認為他這樣說的一個重要原因就是Tapestry的組件機制。Tapestry提供了非常便利的組件定義機制,隨著Tapestry的組件不斷積累,Tapestry的開發將會變得越來越簡單。
本文就用一個實例來看一下Tapestry中是如何添加一個自定義組件的。
Tapestry的內置組件只提供了checkbox,而且只能返回一個boolean,用于表明是否被選中。
比如,要進行一個群眾喜愛的水果調查,選項有: 蘋果,葡萄,桃子,香蕉...,就需要對應每個選項設置一個布爾型變量,顯得比較繁瑣。
這里我們將添加一個組件用于將一組checkbox集中起來返回一個逗號分隔的字符串值。
通過查看Tapestry中的checkbox的源碼(已經附在文章的后面)可以知道,Tapestry可以很容易地通過Request來獲取Form中的變量的值。
遇到的問題:
Tapestry的checkbox組件不允許設置相同的name,如果name相同,Tapestry會自動在name后面添加后綴來使之不同。
If a component renders multiple times, a suffix will be appended to the to id to ensure uniqueness(http://tapestry.apache.org/tapestry5.1/tapestry-core/ref/org/apache/tapestry5/corelib/components/Checkbox.html)。如果各checkbox的name不同,我們無法通過request來獲得一組checkbox的值。
思路:
在頁面模板中不使用tapestry的checkbox組件,而使用Html的checkbox,這樣可以避免tapestry自動修改checkbox的name。
添加一個新的tapestry組件,來映射接受所有同名的checkbox的值,并把值返回給tapestry頁面中對應的變量。這個組件需要有一個屬性,這個屬性的值就是所有同組checkbox的name,這樣,這個組件就可以通過Request來獲取所有相同name的checkbox的值。
代碼:
1 public class CheckBoxGroup extends AbstractField {
2
3 @SuppressWarnings("unused")
4 @Parameter(required = true, autoconnect = true)
5 private String value;
6
7 @Parameter(required = true, autoconnect = true)
8 private String groupName;
9
10 @Inject
11 private Request request;
12
13 @SuppressWarnings("unused")
14 @Mixin
15 private RenderDisabled renderDisabled;
16
17 @Inject
18 private ComponentResources resources;
19
20 @BeginRender
21 void begin(MarkupWriter writer)
22 {
23 writer.element("input", "type", "checkbox",
24 "name", groupName,
25 "id", getClientId(),
26 "style", "display:none");
27
28 resources.renderInformalParameters(writer);
29
30 decorateInsideField();
31 }
32
33 @AfterRender
34 void after(MarkupWriter writer)
35 {
36 writer.end(); // input
37 }
38
39 @Override
40 protected void processSubmission(String elementName)
41 {
42 String elementValue = "";
43 String[] valueArray = request.getParameters(groupName);
44 if ( valueArray != null && valueArray.length > 0 ) {
45 elementValue = valueArray[0];
46 for ( int i = 1; i < valueArray.length; i ++ ) {
47 elementValue += "," + valueArray[i];
48 }
49 }
50 value = elementValue;
51 }
52 }
組件的使用:
-----tml------
<t:CheckBoxGroup t:groupName="literal:bookId" t:value="selectedBooks"/>
<t:loop source="bookList" value="book" encoder="encoder">
<div><input type="checkbox" name="bookId" value="${book.id}"/> ${book.name}</div>
</t:loop>
注意checkBoxGroup的groupName和其他checkbox的name必須一致,checkBoxGroup的value的值就是頁面中的變量名
-----java-----
@SuppressWarnings("unused")
@Property
private final ValueEncoder<Book> encoder = new ValueEncoder<Book>() {
public String toClient(Book value) {
return String.valueOf(value.getId());
}
public Book toValue(String clientValue) {
return bookDao.getBook(Integer.parseInt(clientValue));
}
};
public List<Book> getBookList() {
return bookDao.getBooks();
}
@SuppressWarnings("unused")
@Property
private Book book;
@SuppressWarnings("unused")
@Property
private String selectedBooks;