user2274508
user2274508

Reputation: 261

Is it possible to access Method Annotations in JSP

I would like to use a custom annotation 'T9n' to annotate class properties with String labels. I would rather do this than refer to a messages.properties file that has a weak reference to the property (just defined in the JSP page). I would like to do something like:

Annotation:

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

Class:

public class MyClass {

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

JSP (Spring form JSTL tag):

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

Is this possible? My thoughts at the moment would be to do something with a custom JSP Tag, I cannot find anything from searching around.

Upvotes: 1

Views: 1910

Answers (1)

user2274508
user2274508

Reputation: 261

I implemented a custom tag in the end. I found a good article defining the steps here:

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

My Java code to obtain the T9n value is:

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;
    }
}

So it now looks like this in my JSP:

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

Hope this helps someone else at some point

@Holger - I could have used embedded Java code but this would have looked messy and is not good for presentation level separation.

Upvotes: 1

Related Questions