参数验证

参数验证功能 [1] 是基于 JSR303 实现的,用户只需标识 JSR303 标准的验证 annotation,并通过声明 filter 来实现验证 [2]

Maven 依赖

  1. <dependency>
  2. <groupId>javax.validation</groupId>
  3. <artifactId>validation-api</artifactId>
  4. <version>1.0.0.GA</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.hibernate</groupId>
  8. <artifactId>hibernate-validator</artifactId>
  9. <version>4.2.0.Final</version>
  10. </dependency>

示例

参数标注示例

  1. import java.io.Serializable;
  2. import java.util.Date;
  3. import javax.validation.constraints.Future;
  4. import javax.validation.constraints.Max;
  5. import javax.validation.constraints.Min;
  6. import javax.validation.constraints.NotNull;
  7. import javax.validation.constraints.Past;
  8. import javax.validation.constraints.Pattern;
  9. import javax.validation.constraints.Size;
  10. public class ValidationParameter implements Serializable {
  11. private static final long serialVersionUID = 7158911668568000392L;
  12. @NotNull // 不允许为空
  13. @Size(min = 1, max = 20) // 长度或大小范围
  14. private String name;
  15. @NotNull(groups = ValidationService.Save.class) // 保存时不允许为空,更新时允许为空 ,表示不更新该字段
  16. @Pattern(regexp = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$")
  17. private String email;
  18. @Min(18) // 最小值
  19. @Max(100) // 最大值
  20. private int age;
  21. @Past // 必须为一个过去的时间
  22. private Date loginDate;
  23. @Future // 必须为一个未来的时间
  24. private Date expiryDate;
  25. public String getName() {
  26. return name;
  27. }
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31. public String getEmail() {
  32. return email;
  33. }
  34. public void setEmail(String email) {
  35. this.email = email;
  36. }
  37. public int getAge() {
  38. return age;
  39. }
  40. public void setAge(int age) {
  41. this.age = age;
  42. }
  43. public Date getLoginDate() {
  44. return loginDate;
  45. }
  46. public void setLoginDate(Date loginDate) {
  47. this.loginDate = loginDate;
  48. }
  49. public Date getExpiryDate() {
  50. return expiryDate;
  51. }
  52. public void setExpiryDate(Date expiryDate) {
  53. this.expiryDate = expiryDate;
  54. }
  55. }

分组验证示例

  1. public interface ValidationService { // 缺省可按服务接口区分验证场景,如:@NotNull(groups = ValidationService.class)
  2. @interface Save{} // 与方法同名接口,首字母大写,用于区分验证场景,如:@NotNull(groups = ValidationService.Save.class),可选
  3. void save(ValidationParameter parameter);
  4. void update(ValidationParameter parameter);
  5. }

关联验证示例

  1. import javax.validation.GroupSequence;
  2. public interface ValidationService {
  3. @GroupSequence(Update.class) // 同时验证Update组规则
  4. @interface Save{}
  5. void save(ValidationParameter parameter);
  6. @interface Update{}
  7. void update(ValidationParameter parameter);
  8. }

参数验证示例

  1. import javax.validation.constraints.Min;
  2. import javax.validation.constraints.NotNull;
  3. public interface ValidationService {
  4. void save(@NotNull ValidationParameter parameter); // 验证参数不为空
  5. void delete(@Min(1) int id); // 直接对基本类型参数验证
  6. }

配置

在客户端验证参数

  1. <dubbo:reference id="validationService" interface="org.apache.dubbo.examples.validation.api.ValidationService" validation="true" />

在服务器端验证参数

  1. <dubbo:service interface="org.apache.dubbo.examples.validation.api.ValidationService" ref="validationService" validation="true" />

验证异常信息

  1. import javax.validation.ConstraintViolationException;
  2. import javax.validation.ConstraintViolationException;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import org.apache.dubbo.examples.validation.api.ValidationParameter;
  5. import org.apache.dubbo.examples.validation.api.ValidationService;
  6. import org.apache.dubbo.rpc.RpcException;
  7. public class ValidationConsumer {
  8. public static void main(String[] args) throws Exception {
  9. String config = ValidationConsumer.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml";
  10. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
  11. context.start();
  12. ValidationService validationService = (ValidationService)context.getBean("validationService");
  13. // Error
  14. try {
  15. parameter = new ValidationParameter();
  16. validationService.save(parameter);
  17. System.out.println("Validation ERROR");
  18. } catch (RpcException e) { // 抛出的是RpcException
  19. ConstraintViolationException ve = (ConstraintViolationException) e.getCause(); // 里面嵌了一个ConstraintViolationException
  20. Set<ConstraintViolation<?>> violations = ve.getConstraintViolations(); // 可以拿到一个验证错误详细信息的集合
  21. System.out.println(violations);
  22. }
  23. }
  24. }

  1. 2.1.0 版本开始支持, 如何使用可以参考 dubbo 项目中的示例代码 ↩︎

  2. 验证方式可扩展,扩展方式参见开发者手册中的验证扩展 ↩︎