首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

JSR 303 - Bean Validation 介绍及最佳实践 -2

JSR 303 - Bean Validation 介绍及最佳实践 -2

创建一个包含验证逻辑的简单应用(基于 JSP)在本文中,通过创建一个虚构的订单管理系统(基于 JSP 的 web 应用)来演示如何在 Java 开发过程中应用 Bean Validation。该简化的系统可以让用户创建和检索订单。
系统设计和运用的技术图 1. 系统架构图 1 是报表管理系统的结构图,是典型的 MVC(Model-View-Controller)应用。Controller 负责接收和处理请求,Servlet 扮演 Controller 的角色去处理请求、业务逻辑并转向合适的 JSP 页面。在 Servlet 中对数据进行验证。JSP 扮演 View 的角色以图型化界面的方式呈现 Model 中的数据方便用户交互。Model 就是此系统进行操作的数据模型,我们对这部分加以简化不对数据进行持久化。
数据模型图 2. 数据模型图 2 展示的是订单管理系统的数据模型。
声明了 contraint 的 JavaBean清单 1. Order.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Order {
// 必须不为 null, 大小是 10
@NotNull
@Size(min = 10, max = 10)
private String orderId;
// 必须不为空
@NotEmpty
private String customer;
// 必须是一个电子信箱地址
@Email
private String email;
// 必须不为空
@NotEmpty
private String address;
// 必须不为 null, 必须是下面四个字符串'created', 'paid', 'shipped', 'closed'其中之一
// @Status 是一个定制化的 contraint
@NotNull
@Status
private String status;
// 必须不为 null
@NotNull
private Date createDate;
// 嵌套验证
@Valid
private Product product;


getter 和 setter
}




清单 2. Product.java
1
2
3
4
5
6
7
8
9
10
11
public class Product {
// 必须非空
@NotEmpty
private String productName;
// 必须在 8000 至 10000 的范围内
// @Price 是一个定制化的 constraint
@Price
private float price;

Getter 和 setter
}




清单 3. OrderQuery.java
1
2
3
4
5
6
7
8
9
// 'to'所表示的日期必须在'from'所表示的日期之后
// @QueryConstraint 是一个定制化的 constraint
@QueryConstraint
public class OrderQuery {
private Date from;
private Date to;
… omitted …
Getter and setter
}




定制化的 constraint@Price是一个定制化的 constraint,由两个内置的 constraint 组合而成。
清单 4. @Price 的 annotation 部分
1
2
3
4
5
6
7
8
9
10
11
12
// @Max 和 @Min 都是内置的 constraint
@Max(10000)
@Min(8000)
@Constraint(validatedBy = {})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Price {
String message() default "错误的价格";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}




@Status是一个新开发的 constraint.
清单 5. @Status 的 annotation 部分
1
2
3
4
5
6
7
8
9
@Constraint(validatedBy = {StatusValidator.class})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {
String message() default "不正确的状态 , 应该是 'created', 'paid', shipped', closed'其中之一";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

返回列表