Java – how to reuse fieldlength in form, validation and DDL?
I am developing a spring application that contains a large number of input forms I want to reuse field lengths in UI forms, validation, and JPA annotations There is no elegant way to solve this problem My solution is to use constants to declare the length:
public class Person { public static final int FIRSTNAME_LENGTH = 25; @Column(length=FIRSTNAME_LENGTH) private String firstName; ... }
Then reuse constants in validator and JSP
... <form:input path="firstName" maxlength="<%= Integer.toString(Person.FIRSTNAME_LENGTH) %>"/> ...
This is very verbose
Is there a more elegant solution to this problem?
Solution
It is possible to access information stored in comments In fact, this is their main purpose: to store meta information on classes / methods / fields
import javax.persistence.Column; import javax.persistence.Entity; @Entity public class Person { @Column(length=30) private String firstName; public static void main(String[] args) throws SecurityException,NoSuchFieldException { Object person = new Person(); //find out length System.out.println(person.getClass().getDeclaredField("firstName").getAnnotation(Column.class).length()); } }
You should be able to create some custom tags or beans to extract this information in general
Creating your own annotations is not difficult You might consider creating a that specifies which fields to include in the form, how to render them, descriptions, and so on You can create a generic form Then you may not like mixed domains and presentations