Parameter Validation

Parameter validation in Dubbo

Feature Description

The parameter validation feature is implemented based on JSR303. Users only need to specify validation annotations from the JSR303 standard and implement validation through a declared filter.

Maven Dependency

  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>

Usage Scenario

The server addresses various interface parameter validation issues when providing interface services externally.

Reference Case https://github.com/apache/dubbo-samples/tree/master/dubbo-samples-validation

Usage Method

Parameter Annotation Example

  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 // Cannot be null
  13. @Size(min = 1, max = 20) // Length or size range
  14. private String name;
  15. @NotNull(groups = ValidationService.Save.class) // Cannot be null when saving, can be null when updating, indicating no update to this field
  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) // Minimum value
  19. @Max(100) // Maximum value
  20. private int age;
  21. @Past // Must be a past date
  22. private Date loginDate;
  23. @Future // Must be a future date
  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. }

Group Validation Example

  1. public interface ValidationService { // Default can differentiate validation scenarios by service interface, e.g., @NotNull(groups = ValidationService.class)
  2. @interface Save{} // Interface name same as method, capitalized first letter, used to differentiate validation scenarios, e.g., @NotNull(groups = ValidationService.Save.class), optional
  3. void save(ValidationParameter parameter);
  4. void update(ValidationParameter parameter);
  5. }
  1. import javax.validation.GroupSequence;
  2. public interface ValidationService {
  3. @GroupSequence(Update.class) // Validate Update group rules simultaneously
  4. @interface Save{}
  5. void save(ValidationParameter parameter);
  6. @interface Update{}
  7. void update(ValidationParameter parameter);
  8. }

Parameter Validation Example

  1. import javax.validation.constraints.Min;
  2. import javax.validation.constraints.NotNull;
  3. public interface ValidationService {
  4. void save(@NotNull ValidationParameter parameter); // Validate parameter is not null
  5. void delete(@Min(1) int id); // Directly validate basic type parameter
  6. }

Validate Parameters on Client

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

Validate Parameters on Server

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

Dubbo supports hibernate-validator version <=6.x by default. If using hibernate-validator version 7.x, declare the validation parameter as jvalidationNew.

Validation Exception Information

  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) { // Throws RpcException
  19. ConstraintViolationException ve = (ConstraintViolationException) e.getCause(); // Inside is a nested ConstraintViolationException
  20. Set<ConstraintViolation<?>> violations = ve.getConstraintViolations(); // Can get a collection of detailed validation error information
  21. System.out.println(violations);
  22. }
  23. }
  24. }

Validation methods are extensible. See the developer manual for validation extensions for more information.

Feedback

Was this page helpful?

Yes No

Last modified September 30, 2024: Update & Translate Overview Docs (#3040) (d37ebceaea7)