【问题标题】:JSP tag attributes with different value types具有不同值类型的 JSP 标记属性
【发布时间】:2013-12-13 18:51:18
【问题描述】:

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

我必须使用上面提到的“属性编辑器”吗?那怎么用呢?

【问题讨论】:

    标签: java jsp jsp-tags


    【解决方案1】:

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

    【讨论】:

    • 我可以,但没有任何干净且键入安全的方法吗?
    • @dtrunk 我不知道,也许有人可以回答得更好。您是否尝试使用 String 属性并检查 Locale 是否将转换为 String?虽然它不会比 Object 更安全。
    • 是的,我做到了。它运作良好。我会等一天,如果没有更好的答案,我会接受你的答案。
    【解决方案2】:

    这个怎么样

    <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}" />
    

    【讨论】:

    • 好主意,但这不能回答如何使用具有不同值类型的属性的问题。
    • 好吧,我猜这是真的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 2021-11-21
    • 2012-05-22
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多