This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Bean Validation (jSR-349) is a new feature for Bean Validation (jSR-349).
- Cross-parameter validation (such as password and confirmation password validation)
- Support for EL expressions in messages
- Method parameter/return value validation
- CDI and dependency injection
- Group transformation
Java Bean Validation was first introduced in Hibernate validator 5, and spring4 has just started using Java Bean Validation. Let’s explain Bean Validation in the following ways, which are not necessarily new features:
-
Integrate Java Bean Validation into SpringMVC
- Group authentication, group sequence and cascade authentication
- EL expressions are used in messages
- Method parameter/return value validation
- Custom authentication rules
- Class-level validators
- Script validator
- Cross-parameter, cross-parameter verification
- Mix class-level validators and cross-parameter validators
- Combine multiple validation annotations
- localization
Because most of the time validation is used with web frameworks, and many of you have consulted on things like grouping/cross-parameter validation, this article covers these and is an example of integration with the SpringMVC framework. Other uses (such as integration with JPA) can be found in its official documentation:
- Specification: beanvalidation.org/1.1/spec/
- Hibernate Validator documentation: hibernate.org/validator/
Add hibernate Validator dependencies:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>latest.version</version>
</dependency>
Copy the code
If you want to use EL expressions in messages, make sure the EL expression version is 2.2 or above, and Tomcat7 or above is required.
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
<scope>provided</scope>
</dependency>
Copy the code
Make sure that the Web container you use has the appropriate version of the EL JAR package.
Presentation of Web services
@Controller
public class HelloWorldController {
@RequestMapping("/validate/hello")
public String validate(@Valided @ModelAttribute("user") UserModel user, Errors errors) {
if(errors.hasErrors()) {
return "validate/error";
}
return "redirect:/success"; }}Copy the code
Hard-coded error messages
Specify the error message directly on the validation constraint annotation as follows:
@notnull (message = "username cannot be empty ")
@length (min=5, Max =20, message=" user name must be between 5 and 20 ")
@pattern (regexp = "^[a-za-z_]\\w{4,19}$", message = "user name must start with an alphabetic underscore and may consist of alphanumeric underscores ")
private String username;
Copy the code
As shown above, error messages are hardcoded, which is not recommended because it is not appropriate in the following scenarios:
- In an international scenario, different error messages need to be displayed for different countries.
- When you need to replace the error message, it is cumbersome to find the appropriate class to replace it and recompile it for distribution.
Handoff to resource files
The default error message file is/org/hibernate/validator/ValidationMessages properties, as shown in the figure below:
public class User implements Serializable {
@NotNull(message = "{user.id.null}")
private Long id;
@NotEmpty(message = "{user.name.null}")
@Length(min = 5, max = 20, message = "{user.name.length.illegal}")
@ the Pattern (regexp = "[a zA - Z] {5, 20}", message = "{user. Name. Illegal}")
private String name;
@NotNull(message = "{user.password.null}")
private String password;
}
Copy the code
Error message content
The default error key values are as follows:
-
The message key defaults to: fully qualified class name for validation constraint annotations. Message.
-
In our previous test file, error message keys were used by default. How do I customize the error message file and error message keys?
Custom error message file and error message key values
- The custom error message key values in the error message file override the default error message key values in the error message file.
- Custom error message files are internationalized.
Define error message files
Under the root of class loading path to create ValidationMessages. The properties files, such as in the SRC directory to create automatically copied to the class loading path under the root of key value and add the following news
Custom error message file and error message key Values The error message key values in the custom error message file overwrite the default error message file. Our custom error message file is internationalized.
Javax.mail. Validation. Constraints. The Pattern. The message = username must start with a letter or underscore, you can talk with alphanumeric behind the underline, length between 5 and 20.
-
org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
-
org.hibernate.validator.HibernateValidator
This error message key lookup will be under the classpath ValidationMessages. The properties of find, could not find the error message to the default file to find.
Message key lookup using Spring’s MessageSource Bean If our environment is integrated with Spring or should use the messaging support provided by Spring, the configuration is as follows
- org.springframework.context.support.ReloadableResourceBundleMessageSource
- The basename: the classpath: messages
- FileEncodings: utf-8
- CacheSeconds: 120
Add the following error message to the message file SRC /messages.properties:
- Javax.mail. Validation. Constraints. The Pattern. The message = username must start with a letter or underscore, you can talk with alphanumeric behind the underline, length between 5 and 20.
When the messageSource Bean is configured, the following error message keys are automatically generated for validated objects by default:
- Validation error annotation simple class name. Validate object name. Field name
- Validation error annotation simple class name. The field name
- Validation error annotation simple class name. Field type Fully qualified class name
- Validation error annotation simple class name
The priorities used are: from high to low, that is, the first one has the highest priority, and all the above default error keys have a higher priority than the custom error keys.
public String pattern(@Valided @ModelAttribute("model") PatternModel model, Errors errors)
Copy the code
The following error message key is automatically generated:
- Pattern.model.value= Validate error annotation simple class name. Validate object name. Field name
- Pattern. Value = Validates the error annotation simple class name. The field name
- Pattern.java.lang.String= Validate error annotation simple class name. Field type Fully qualified class name
- Pattern= Validate error annotation simple class name
Custom error message key values
In most scenarios, these two approaches are not sufficient for our needs, so we need to customize the error message key.
public class PatternModel {
@ the Pattern (regexp = "^ [a zA - Z_] [\ \ w] {4} 3 $", message =" {user. The name. The error} ")
private String value;
}
Copy the code
Add the following error message to the message file SRC /messages.properties:
User.name. error= The format of the user name is invalid
Add the following error message to the message file SRC /messages.properties:
@Length(min=5, max=20, message="{user.name.length.error}")
Copy the code
- User.name.length. error= The user name must contain 5 to 20 characters
The 5-20 in the error message should be taken from the @Length validation constraint annotation rather than hard-coded in the error message, so we need placeholder support:
@Length(min=5, max=20, message="{user.name.length.error}")
Copy the code
The error message could be written as follows: The user name must be between {min}-{Max}.
Error message placeholder rules: {validate annotation attribute name} :
-
@length has min and Max attributes, which can be obtained by {min} and {Max} in the error message file.
-
@max has a value attribute, which can be obtained by {value} in the error message file.
User.name.length. error= The length of the user name must be between {min} and {Max}Copy the code
The processing of multiple validation parameters on the function processing method
When we need to validate multiple model objects on a functional processing method, we need to obtain validation results in the following form:
@RequestMapping("/validate/multi")
public String multi(
@Valid @ModelAttribute("a") A a, BindingResult aErrors,
@Valid @ModelAttribute("b") B b, BindingResult bErrors) {
if(aErrors.hasErrors()) { // If a model object fails to validate
return "validate/error";
}
if(bErrors.hasErrors()) { // If a model object fails to validate
return "validate/error";
}
return "redirect:/success";
}
Copy the code
Each model object needs to be followed by an Errors or BindingResult object to hold validation results, which can be used inside the method body to select the page to jump to in case of an error.