如何重用FieldLength参数形式,验证和DDL? [英] How to reuse fieldlength in form, validation and ddl?

查看:143
本文介绍了如何重用FieldLength参数形式,验证和DDL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作有很多的输入表单的Spring应用程序。我想重用的UI形式,验证和JPA注释字段长度。有没有解决这个优雅的方式。我当时的解决方案是,使用常量来声明长度:

I'm working on an Spring application with lots of input forms. I'd like to reuse the field length in the UI-form, validation and JPA annotations. Is there an elegant way to solve this. My solution at the moment 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;

   ...
}

,然后再用在验证不断,而JSP

and then reuse the constant in the Validator and the Jsp

...

<form:input path="firstName" 
    maxlength="<%= Integer.toString(Person.FIRSTNAME_LENGTH) %>"/>

...

这是pretty冗长。

which is pretty verbose.

有没有更优雅的解决这个问题呢?

Is there any more elegant solution to this problem?

推荐答案

它很可能访问存储在注释中的信息。事实上,这是他们的主要目的:一类/方法/存储领域的元信息。
下面是如何访问存储在一个@Column注释的长度的示例:

It's quite possible to access the information stored in annotations. In fact, this is their main purpose: storing meta information on a class/ method/ field. Here is an example of how to access the length stored in a @Column annotation:

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 tag or bean to extract this info generically.

这不难创建自己的注解。你可以考虑创建一个指定哪些字段要包含的形式,他们应该如何呈现,描述等比你可以创建一个通用的形式。话又说回来,你可能不喜欢混合域和presentation。

It's not difficult to create your own annotations. You could consider creating one that specifies which fields are to be included on the form, how they should be rendered, description, etc. Than you could create a generic form. Then again you may not like to mix domain and presentation.

这篇关于如何重用FieldLength参数形式,验证和DDL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆