如何在表单、验证和 ddl 中重用字段长度? [英] How to reuse fieldlength in form, validation and ddl?

查看:28
本文介绍了如何在表单、验证和 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;

   ...
}

然后在 Validator 和 Jsp 中重用常量

and then reuse the constant in the Validator and the Jsp

...

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

...

这很冗长.

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

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

您应该能够创建一些自定义标记或 bean 来一般地提取此信息.

You should be able to create some custom tag or bean to extract this info generically.

创建自己的注释并不难.您可以考虑创建一个指定表单中要包含哪些字段、它们应该如何呈现、描述等.而不是您可以创建一个通用表单.再说一次,您可能不喜欢将域和演示文稿混合使用.

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.

这篇关于如何在表单、验证和 ddl 中重用字段长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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