tapestry 中使用枚举类型作为组件参数的方法

转自:http://tapestry.apache.org/enum-parameter-recipe.html

 

It's not uncommon to create a component that has a bit of complex behavior that you want to be able to easily control, and an enumerated type (a Java enum) seems like the right approach.

 

Our example comes from Tapestry's Select component, which has a blankOption parameter that an enum type.

 

Let's start with the enum type itself:

 


BlankOption.java

public enum BlankOption
{
    /**
     * Always include the blank option, even if the underlying property is required.
     */
    ALWAYS,

    /**
     * Never include the blank option, even if the underlying property is optional.
     */
    NEVER,

    /**
     * The default: include the blank option if the underlying property is optional.
     */
    AUTO;
}
 

 

Next, we define the parameter:

 


Select.java (partial)

/**

* Controls whether an additional blank option is provided. The blank option precedes all other options and is never

* selected. The value for the blank option is always the empty string, the label may be the blank string; the

* label is from the blankLabel parameter (and is often also the empty string).

*/

@Parameter(value = "auto", defaultPrefix = BindingConstants.LITERAL)

private BlankOption blankOption;


Note the use of literal as the default prefix; this allows us to use the name of the option in our template, e.g. <t:select blankoption="never" .../>. Without the default prefix setting, "never" would be interpreted as a property expression (and you'd see an error when you loaded the page).

 

The final piece of the puzzle is to inform Tapestry how to convert from a string, such as "never", to a BlankOption value.

 


TapestryModule.java (partial)

  public static void contributeTypeCoercer(Configuration<CoercionTuple> configuration)
    {
       . . .
       
       add(configuration, BlankOption.class);

       . . .
    }

    private static <T extends Enum> void add(Configuration<CoercionTuple> configuration, Class<T> enumType)
    {
        configuration.add(CoercionTuple.create(String.class, enumType, StringToEnumCoercion.create(enumType)));
    }
 

 

The TypeCoercer service is ultimately responsible for converting the string to a BlankOption, but we have to tell it how, by contributing an appropriate CoercionTuple. The CoercionTuple identifies the source and target types (String and BlankOption), and an object to perform the coercion (an instance of StringToEnumCoercion, via the create() static method).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值