MDP
MDP

Reputation: 4267

How to retrieve the annotations (JPA and Hibernate) of a field of a POJO in a JSP page

I have a Spring MVC web application where I use JPA and Hibernate annotations (plus my own custom annotations). Let's say I have this object:

public class User{      
    @Size(min = 2, max = 20)
    private String name;
}

Is there a way to get the annotation values of my object from a jsp page? Something like

${User.name.Size.min}

I hope I've been clear.

Thank you in advance

Upvotes: 1

Views: 65

Answers (2)

rptmat57
rptmat57

Reputation: 3787

another way you can do this is by creating a constant that you would use in your annotation:

public class User {      

    public static final int SIZE_NAME_MIN = 2;

    public static final int SIZE_NAME_MAX = 20;

    @Size(min = SIZE_NAME_MIN, max = SIZE_NAME_MAX)
    private String name;
}

you can keep that constant either in the class or somewhere else

Upvotes: 1

Essex Boy
Essex Boy

Reputation: 7950

Sounds like you shouldn't be doing this, but this may get you started. I would create another class for the reflection. The jsp will look for the properties by getters.

public class UserAnnotationResolver {

    public static FieldAnnotationResolver getName() {
        try {
            return new UserAnnotationResolver().new FieldAnnotationResolver(User.class.getDeclaredField("name"));
        } catch (NoSuchFieldException e) {

        }
        return null;
    }

    public class FieldAnnotationResolver {

        private Field field;

        public FieldAnnotationResolver(Field field) {
            this.field = field;
        }

        SizeAnnotationResolver getSize() {
            return new SizeAnnotationResolver(field.getAnnotationsByType(Size.class)[0]);
        }
    }

    public class SizeAnnotationResolver {

        Size size;

        public SizeAnnotationResolver(Size size) {
            this.size = size;
        }

        public int getMin() {
            return size.min();
        }

        public int getMax() {
            return size.max();
        }

    }

}

Upvotes: 1

Related Questions