---
title: "在Tapestry中通用的property selection model"
author: "tapestry"
date: "2006-12-07T12:07:08Z"
tags: ["Apache", "HTML", "Tapestry"]
slug: "tapestry-property-selection-model"
draft: false
lastmod: "2006-12-07T12:07:08Z"
id: 37739
url: "https://tapestry.iteye.com/blog/37739"
---

Tapestry中构建选择列表需要使用IPropertySelectionModel，Model可以映射选择列表中的Label和Option，Tapestry中已经提供一个常用的StringSelectonModel,具体组件使用如下：&lt;o:p&gt;&lt;/o:p&gt;

Html代码&lt;o:p&gt;&lt;/o:p&gt;

 

Java代码

java 代码

 

01. public abstract class DetailsPage extends BasePage {
02. public static final IPropertySelectionModel GENDER\_MODEL =
03. new StringPropertySelectionModel(new String\[] { "Unspecified", "Female", "Male" });
04. public abstract String getGender();
05. public void formSubmit(IRequestCycle cycle) {
06. // Process form submission
07. String genderSelection = getGender();
08. ...
09. }
10. }

      开发中比较常见的选择列表就是类别的选择，，一般是新建一个类别的SelectionModel，例如如下代码

java 代码

 

01. public class TypeSelectionModel implements IPropertySelectionModel, Serializable {
02. private List TypeList;
03. public ItemSelectionModel(List typeList) {
04. this. typeList = typeList;
05. }
06. public int getOptionCount() { return typeList.size(); }
07. public Object getOption(int index) {
08. return ((Type)typeList.get(index)).getId();
09. }
10. public String getLabel(int index) {
11. return ((Type) typeList.get(index)).getName();
12. }
13. public String getValue(int index) { return Integer.toString(index); }
14. public Object translateValue(String value) {
15. return getOption(Integer.parseInt(value));
16. }
17. }

这只是传统方法，开发中的类别如果多了，每一个都要新建一个SelectionModel。

下面是在[Tapestry JumpStart](http://files.doublenegative.com.au/jumpstart/)里看到的通用的SelectionModel，感觉比较不错，现介绍给大家，具体代码如下：

java 代码

 

01. package com.javaeye.tapestrying.selectionModel;
02. import java.lang.reflect.InvocationTargetException;
03. import java.lang.reflect.Method;
04. import java.util.ArrayList;
05. import java.util.List;
06. import org.apache.tapestry.form.IPropertySelectionModel;
07. public class ObjectPropertySelectionModel implements IPropertySelectionModel {
08. private List \_list;
09. private Method \_methodToGetLabel = null;
10. private Method \_methodToGetOption = null;
11. private boolean \_allowNoSelection = false;
12. private String \_noSelectionMessage = null;
13. private int \_offset = 0;
14. public ObjectPropertySelectionModel() {
15. \_list = new ArrayList();
16. throw new UnsupportedOperationException("Do not use the default constructor.");
17. }
18. /\**
19. \*
20. * @param list
21. *            the list of objects to represent in a PropertySelection
22. *            component. WARNING: The objects in the list MUST implement
23. *            equals(Object obj) and hashCode(), and if they are EJB3
24. *            Entities those methods MUST return the same thing for
25. *            different instances of the same detached entity (eg. by
26. *            matching on Id only).
27. * @param clazz
28. *            the class of objects in the list.
29. * @param nameOfMethodToGetLabel
30. *            the name of the method that PropertySelection must invoke on
31. *            each object in the list to get its label to display in the
32. *            list on the page. For example, the method name might be
33. *            "getShortName".
34. * @param nameOfMethodToGetOption
35. *            the name of the method that PropertySelection must invoke on
36. *            an object when it has been selected. The result is put into
37. *            the property named in the "value" parameter of the
38. *            PropertySelection. For example, the method name might be
39. *            "getKey". If you want the result to be the the whole object
40. *            then set this argument to null.
41. \*
42. \*/
43. public ObjectPropertySelectionModel(Listextends Object&gt; list, Class clazz, String nameOfMethodToGetLabel,
44. String nameOfMethodToGetOption) {              this(list, clazz, nameOfMethodToGetLabel, nameOfMethodToGetOption, false, null);
45. }
46. /\**
47. \*
48. * @param list
49. *            the list of objects to represent in a PropertySelection
50. *            component. WARNING: The objects in the list MUST implement
51. *            equals(Object obj) and hashCode(), and if they are EJB3
52. *            Entities those methods MUST return the same thing for
53. *            different instances of the same detached entity (eg. by
54. *            matching on Id only).
55. * @param clazz
56. *            the class of objects in the list.
57. * @param nameOfMethodToGetLabel
58. *            the name of the method that PropertySelection must invoke on
59. *            each object in the list to get its label to display in the
60. *            list on the page. For example, the method name might be
61. *            "getShortName".
62. * @param nameOfMethodToGetOption
63. *            the name of the method that PropertySelection must invoke on
64. *            an object when it has been selected. The result is put into
65. *            the property named in the "value" parameter of the
66. *            PropertySelection. For example, the method name might be
67. *            "getKey". If you want the result to be the the whole object
68. *            then set this argument to null.
69. * @param allowNoSelection
70. *            If true then adds an element to the start of the list. Its
71. *            option is null.
72. * @param noSelectionLabel
73. *            If null then no label. A typical label might be "Select...".
74. \*
75. \*/
76. public ObjectPropertySelectionModel(Listextends Object&gt; list, Class clazz, String nameOfMethodToGetLabel,
77. String nameOfMethodToGetOption, boolean allowNoSelection, String noSelectionLabel) {
78. try {
79. \_list = list;
80. \_methodToGetLabel = clazz.getMethod(nameOfMethodToGetLabel, (Class\[]) null);
81. if (nameOfMethodToGetOption != null) {
82. \_methodToGetOption = clazz.getMethod(nameOfMethodToGetOption, (Class\[]) null);
83. }
84. \_allowNoSelection = allowNoSelection;
85. if (\_allowNoSelection) {
86. \_noSelectionMessage = noSelectionLabel;

<!--THE END-->

01. \_offset = 1;
02. }
03. }
04. catch (SecurityException e) {
05. throw new IllegalStateException(e);
06. }
07. catch (NoSuchMethodException e) {
08. throw new IllegalArgumentException("Given nameOfMethodToGetLabel=\\"" + nameOfMethodToGetLabel + "\\", nameOfMethodToGetOption=\\""
09. + nameOfMethodToGetOption + "\\", class=\\"" + clazz + "\\".", e);
10. }
11. }
12. public int getOptionCount() {
13. return \_list.size() + \_offset;
14. }
15. public Object getOption(int index) {
16. if (\_allowNoSelection) {
17. if (index &lt; \_offset) {
18. return null;
19. }
20. }
21. Object o = \_list.get(index - \_offset);
22. if (\_methodToGetOption == null) {
23. return o;
24. }
25. else {
26. try {
27. Object option = \_methodToGetOption.invoke(o, (Object\[]) null);
28. return option;
29. }
30. catch (IllegalArgumentException e) {
31. throw new IllegalStateException("Problem with the given methodToGetOption \\"" + \_methodToGetOption + "\\": ", e);
32. }
33. catch (IllegalAccessException e) {
34. throw new IllegalStateException("Problem with the given methodToGetOption \\"" + \_methodToGetOption + "\\": ", e);
35. }
36. catch (InvocationTargetException e) {
37. throw new IllegalStateException("Problem with the given methodToGetOption \\"" + \_methodToGetOption + "\\": ", e);
38. }
39. }
40. }
41. public String getLabel(int index) {
42. if (\_allowNoSelection) {
43. if (index &lt; \_offset) {
44. return \_noSelectionMessage;
45. }
46. }
47. Object o = \_list.get(index - \_offset);
48. try {
49. String label = \_methodToGetLabel.invoke(o, (Object\[]) null).toString();
50. return label;
51. }
52. catch (IllegalArgumentException e) {
53. throw new IllegalStateException("Problem with the given methodToGetLabel \\"" + \_methodToGetOption + "\\": ", e);
54. }
55. catch (IllegalAccessException e) {
56. throw new IllegalStateException("Problem with the given methodToGetLabel \\"" + \_methodToGetOption + "\\": ", e);
57. }
58. catch (InvocationTargetException e) {
59. throw new IllegalStateException   ("Problem with the given methodToGetLabel \\"" + \_methodToGetOption + "\\": ", e);
60. }
61. }
62. public String getValue(int index) {
63. return Integer.toString(index);
64. }
65. public Object translateValue(String value) {
66. return value == null ? null : getOption(Integer.parseInt(value));
67. }
68. }

具体使用如下，假如现在有一个配件类型的类

java 代码

1. public class FittingType {
2. private Long id;
3. private String name;
4. private Set&lt;fitting&gt;&lt;/fitting&gt; fittings = new HashSet&lt;fitting&gt;&lt;/fitting&gt;();
5. //getter and setter
6. }

&lt;o:p&gt;&lt;/o:p&gt;

创建配件类时，需要选择配件类型

java 代码

01. private IPropertySelectionModel fittingTypeSelectionModel;
02. public IPropertySelectionModel getFittingTypeSelectionModel() {
03. if (fittingTypeSelectionModel == null) {
04. List&lt;fittingtype&gt;&lt;/fittingtype&gt; fittingTypes = getFittingTypeService().findAll();
05. fittingTypeSelectionModel = new ObjectPropertySelectionModel(
06. fittingTypes, FittingType.class, "getName", "getId", true,
07. "选择分类");
08. }
09. return fittingTypeSelectionModel;
10. }
11. public abstract Long getFittingTypeId();
12. public ILink onSave() {
13. //其他
14. if (getFittingTypeId() != null) {
15. fitting.setType(getFittingTypeService()
16. .findByID(getFittingTypeId()));
17. }
18. //其他
19. }

Html中定义组件&lt;o:p&gt;&lt;/o:p&gt;

java 代码

1. "type@PropertySelection" model="ognl:fittingTypeSelectionModel" value="ognl:fittingTypeId" displayName="配件类型"/&gt;

&lt;o:p&gt; &lt;/o:p&gt;

具体定义中

fittingTypeSelectionModel = **new** ObjectPropertySelectionModel(&lt;o:p&gt;&lt;/o:p&gt;

                  fittingTypes, FittingType.**class**, "getName", "getId", **true**,&lt;o:p&gt;&lt;/o:p&gt;

                  "选择分类");&lt;o:p&gt;&lt;/o:p&gt;

       }&lt;o:p&gt;&lt;/o:p&gt;

参数1：候选的List

参数2：类别

参数3：label的getter方法

参数4：option的getter方法

参数5：是否允许没有选项

参数6：没有选项时的label

&lt;o:p&gt; &lt;/o:p&gt;

好了，项目中又多了个通用的东西，开发时又可以happy了。

java 代码

 

1. "@PropertySelection" model="ognl:@com.myexample.DetailsPage@GENDER\_MODEL" value="ognl:gender"/&gt;