具有不同值类型的JSP标记属性

时间:2013-12-13 18:51:19

标签: java jsp jsp-tags

是否可以为其属性设置具有不同值类型的JSP标记?

<tag>
    <name>init</name>
    <tag-class>com.example.InitTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>locale</name>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

public class InitTag extends SimpleTagSupport {
    private Locale locale;

    public InitTag() {
        setLocale(Locale.getDefault());
    }

    public void setLocale(String locale) {
        setLocale(SetLocaleSupport.parseLocale(locale));
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }
}

现在我希望能够使用Locale对象以及String对象作为属性值:

<mytag:init locale="en" />
or
<mytag:init locale="${anyLocaleObject}" />

但是得到这个例外:org.apache.jasper.JasperException: Unable to convert string "en" to class "java.util.Locale" for attribute "locale": Property Editor not registered with the PropertyEditorManager

我是否必须使用这个提到的“属性编辑器”?那怎么用?

2 个答案:

答案 0 :(得分:2)

您可以使用Object类型的属性并动态检查它是String还是Locale或其他。

答案 1 :(得分:1)

这个怎么样

<tag>
    <name>init</name>
    <tag-class>com.example.InitTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>localeCode</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>locale</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

public class InitTag extends SimpleTagSupport {

    private Locale locale;

    public InitTag() {
        setLocale(Locale.getDefault());
    }

    public void setLocaleCode(String locale) {
        setLocale(SetLocaleSupport.parseLocale(locale));
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }
}

在JSP中

<mytag:init localeCode="en" />
OR
<mytag:init localeCode="{anyLocaleCode}" />
OR
<mytag:init locale="${anyLocaleObject}" />
相关问题