In the project, most of the front-end checks are used, such as the JS check in the page and the form form using the bootstrap checksum. However, for higher security requirements, it is recommended to verify on the service side.
Service-side check:
- Control Layer Controller: Verifies the legality of the parameters requested by the page. In the server-side control layer controller checksum, the client type is not distinguished.
- Business Layer Service (use more): Mainly check the key business parameters, limited to the parameters used in the service interface.
- Persistence Layer DAO: It is generally not verified.
Environment integration
1. Add Jar Package:
Here, using the Hibernate-validator implementation (version: Hibernate-validator-4.3.0.final-dist.zip), add the following jar package to the Classpath (web-inf/lib):
Dist/lib/required/validation-api-1.0.0.ga.jar JSR-303 Specification API pack
Dist/hibernate-validator-4.3.0.final.jar Hibernate Reference Implementation
2. Always add support for JSR-303 validation framework in spring configuration
<!--check error message profile--<BeanId="Messagesource"class="Org.springframework.context.support.ReloadableResourceBundleMessageSource" ><!--resource file name--<PropertyName="Basenames" ><List><Value>classpath:customvalidationmessages</value> </list> </property> <!--resource file encoding format- < Property name="fileencodings" value="Utf-8"/> <!--cache time for resource file content, in seconds--and < Property name="cacheseconds" value="/> </bean> "
<!--validators--<BeanId="Validator"class="Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" > <!-- Hibernate Validator- < property name="Providerclass" value=" Org.hibernate.validator.HibernateValidator "/> <!--Specify the resource file used by the checksum, configure the checksum error message in the file, If not specified, the default is to use Validationmessages.properties-- < property name= "Classpath" Validationmessagesource " ref=" Messagesource "/> </bean>
Auto-Registration Validator
<mvc:annotation-driven conversion-service="conversionService" validator="validator"> </mvc:annotation-driven>
Example description
Example one:
import javax.validation.constraints.NotNull; public class UserModel { @NotNull(message="{username.not.empty}") private String username; }
Specifies that this username field is not allowed to be empty by @notnull, and when validation fails, the error message "Username.not.empty" is obtained from the previously specified Messagesource, where only the "{Error message key value}" is passed The format specified can be obtained from Messagesource.
@Controller public class HelloWorldController { @RequestMapping("/validate/hello") public String validate(@Valid @ModelAttribute("user") UserModel user, Errors errors) { if(errors.hasErrors()) { return "validate/error"; } return "redirect:/success"; } }
By annotating @valid on the Command object, you tell spring MVC that this command object needs to be JSR-303 validated after it has been bound, and if the validation fails, the error message is added to the errors Error object.
Pages to show after validation failure (/WEB-INF/JSP/ERROR.JSP)
<%@ page language= "java" Contenttype= "text/html; Charset=utf-8 "Pageencoding=" UTF-8 "%> <% @taglib prefix=< Span class= "hljs-string" > "form" Uri= "Http://www.springframework.org/tags/form"%> Span class= "Hljs-tag" ><form:form commandName= "user" > <form:errors path= "*" cssStyle= "color:red" ></form:errors> <br/> </ form:form>
Enter Http://localhost:8080/validate/hello in the browser address bar, that is, there is no username data, the request will be directly to the authentication failure interface and display the error message "User name cannot be empty", if requested with "? Username= "Zhang" will be redirected to the success page.
Example two:
public class Items { private Integer id; @Size(min=1,max=20,message="{items.name.length.error}") private String name; @NotNull(message="{items.createtime.isNULL}") private Date createtime; 省略set()和get()...}
public String editItemsSubmit(Model model, @Validated Items items, BindingResult bindingResult) throws Exception { if(bindingResult.hasErrors()){ List<ObjectError> allErrors = bindingResult.getAllErrors(); for(ObjectError objectError:allErrors) { System.out.println(objectError.getDefaultMessage()); } //可以直接使用model将提交pojo回显到页面 model.addAttribute("items",items); // 出错重新到商品修改页面 return "items/editItems"; } return "success"; }
<TableWidth="100%"Border=1><Tr><Td> Product Name</Td><Td><Form:inputType="Text"Path="Items.name"Value="${items.name}"/></Td><Form:errorsPath="Items.name"/></tr><tr> <td> product production date </ td> <td> <input type= "text" name= "Createtime" value= "<fmt:formatdate value=" ${ Items.createtime} "pattern=" yyyy-mm-dd HH:mm:ss "/>"/ ></td></ TR>
Then the JSP page is still the previous page, and can display the input is not legal and through <form:errors path="items.name"/>
the display, this is obviously more simple.
When we configure the Messagesource bean, the default is to automatically generate the following error message key for the validated object:
Validation error annotations Simple class name. Verify the object name. Field Name
Validation error annotations Simple class name. Field Name
Validation error annotations Simple class name. field type fully qualified class name
Validation error annotations Simple class name
The priority used is high-to-low, which is the highest priority in the front, and all of the above default error message keys have precedence over the custom error message key.
such as test cases
Public String pattern (@Valid @ModelAttribute ("model") Patternmodel model, Errors Errors)
The following error message key is automatically generated:
Pattern.model.value= validation error annotations Simple class name. Verify the object name. Field Name
Pattern.value= validation error annotations Simple class name. Field Name
pattern.java.lang.string= validation error annotations Simple class name. field type fully qualified class name
pattern= validation error Annotations Simple class name
The built-in validation constraint annotations are shown in the following table (excerpted from Hibernate validator Reference):
validation Annotations |
Validating the data type |
Description |
@AssertFalse |
Boolean,boolean |
Verify that the element value of the annotation is false |
@AssertTrue |
Boolean,boolean |
Verify that the element value of the annotation is true |
@NotNull |
Any type |
Verify that the element value of the annotation is not null |
@Null |
Any type |
Verify that the element value of the annotation is null |
@Min (value= value) |
Bigdecimal,biginteger, Byte, short, int, long, and so on any number or charsequence (stored as a numeric) subtype |
Verifies that the element value of the annotation is greater than or equal to the value specified by @min |
@Max (value= value) |
Same as the @min requirements. |
Verifies that the element value of the annotation is less than or equal to the value specified by @max |
@DecimalMin (value= value) |
Same as the @min requirements. |
Verifies that the element value of the annotation is greater than or equal to the value specified by @ decimalmin |
@DecimalMax (value= value) |
Same as the @min requirements. |
Verifies that the element value of the annotation is less than or equal to the value specified by @ Decimalmax |
@Digits (integer= integer digits, fraction= decimal place) |
Same as the @min requirements. |
To verify the integer and maximum number of decimal digits for the element value of the annotation |
@Size (min= lower limit, max= upper limit) |
String, Collection, Map, array, etc. |
Verifies that the element value of the annotation is within a specified interval of min and max (inclusive), such as character length, collection size |
@Past |
Java.util.Date, Java.util.Calendar; Joda date type of the time class library |
Verify that the annotation's element value (date type) is earlier than the current time |
@Future |
Same as the @past requirements |
Verify that the annotation's element value (date type) is later than the current time |
@NotBlank |
Charsequence Sub-type |
Verifies that the element value of the annotation is not null (NOT NULL, the first space is removed after the length is 0), differs from @notempty, that the @NotBlank is applied only to strings and that the first space of the string is stripped when compared |
@Length (min= lower limit, max= upper limit) |
Charsequence Sub-type |
Validates the element value length of annotations within min and Max intervals |
@NotEmpty |
Charsequence subtype, Collection, Map, array |
Verifies that the element value of the annotation is not null and is not empty (string length is not 0, collection size is not 0) |
@Range (min= min, max= max) |
Bigdecimal,biginteger,charsequence, Byte, short, int, long, etc. atomic type and packing type |
Verifies that the element value of the annotation is between the minimum and maximum values |
@Email (regexp= Regular expression, flag= flag pattern) |
Charsequence subtype (such as String) |
Verify that the element value of the annotation is email, or you can specify a custom email format via REGEXP and flag |
@Pattern (regexp= Regular expression, flag= flag pattern) |
String, the subtype of any charsequence |
Validates that the element value of the annotation matches the specified regular expression |
@Valid |
Any non-atomic type |
Specifies the object that the recursive validation is associated with, such as having an Address object property in the user object, if you want to validate the address object together when validating the user object, then add @valid annotations on the Address object to cascade validation |
Only the most validation constraint annotations provided by Hibernate Validator are listed here, please refer to Hibernate Validator Official documentation for additional validation constraint annotations and custom validation constraint annotation definitions.
Reference: http://jinnianshilongnian.iteye.com/blog/1733708
http://blog.csdn.net/u012706811/article/details/51079740
SPRINGMVC data Check (JSR-303)