【问题标题】:Is it possible to access Method Annotations in JSP是否可以在 JSP 中访问方法注解
【发布时间】:2013-10-22 08:49:42
【问题描述】:

我想使用自定义注释“T9n”来用字符串标签注释类属性。我宁愿这样做,也不愿引用对属性有弱引用的messages.properties 文件(刚刚在JSP 页面中定义)。我想做类似的事情:

注释:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface T9n {
    String value();
}

类:

public class MyClass {

    @T9n("My Variable")
    private String variableName;
}

JSP(Spring表单JSTL标签):

<form:label path="variableName"><!-- Access T9n annotation here --></form:label>
<form:input path="variableName" />

这可能吗?我目前的想法是使用自定义 JSP 标签做一些事情,但我无法通过搜索找到任何东西。

【问题讨论】:

  • 据我所知,您可以在 JSP 中嵌入任何 Java 代码,因此您应该能够仅嵌入在不涉及 JSP 时将使用的直接代码。
  • @Holger 在 JSP 中嵌入 Java(即 scriptlet)通常被认为是不好的做法。

标签: java jsp spring-mvc annotations jstl


【解决方案1】:

最后我实现了一个自定义标签。我在这里找到了一篇定义步骤的好文章:

http://www.codeproject.com/Articles/31614/JSP-JSTL-Custom-Tag-Library

我获取T9n值的Java代码是:

public class T9nDictionaryTag extends TagSupport {

    private String fieldName;
    private String objectName;

    public int doStartTag() throws JspException {
        try {
            Object object = pageContext.getRequest().getAttribute(objectName);
            Class clazz = object.getClass();
            Field field = clazz.getDeclaredField(fieldName);

            if (field.isAnnotationPresent(T9n.class)) {
                T9n labelLookup = field.getAnnotation(T9n.class);
                JspWriter out = pageContext.getOut();
                out.print(labelLookup.value());
            }

        } catch(IOException e) {
            throw new JspException("Error: " + e.getMessage());
        } catch (SecurityException e) {
             throw new JspException("Error: " + e.getMessage());
        } catch (NoSuchFieldException e) {
             throw new JspException("Error: " + e.getMessage());
        }       
        return EVAL_PAGE;
    }

    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public void setObjectName(String objectName) {
        this.objectName = objectName;
    }
}

所以它现在在我的 JSP 中看起来像这样:

<form:label path="variableName"><ct:t9n objectName="myObject" fieldName="variableName" /></form:label>
<form:input path="variableName" />

希望这在某些时候可以帮助其他人

@Holger - 我本可以使用嵌入式 Java 代码,但这看起来很混乱,不利于表示层级分离。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2016-11-24
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多