Use hibernate-validate and springmvcvalidate in spring MVC

Source: Internet
Author: User

Use hibernate-validate and springmvcvalidate in spring MVC

Add spring MVC. xml

1 <! -- Internationalization configuration --> 2 <bean id = "localeResolver" class = "org. springframework. web. servlet. i18n. cookieLocaleResolver "/> 3 <bean id =" messageSource "class =" org. springframework. context. support. reloadableResourceBundleMessageSource "> 4 <property name =" basenames "> 5 <list> 6 <value> classpath: resource/ValidationMessages </value> 7 </list> 8 </property> 9 <property name = "useCodeAsDefaultMessage" value = "true"/> 10 </ Bean> 11 <! -- Register the validators --> 12 <mvc: annotation-driven validator = "validator"/> 13 14 <bean id = "validator" class = "org. springframework. validation. beanvalidation. localValidatorFactoryBean "> 15 <property name =" providerClass "value =" org. hibernate. validator. hibernateValidator "/> 16 <! -- Here the configuration will use the messageSource --> 17 <property name = "validationMessageSource" ref = "messageSource"/> 18 </bean>

 

Resource file (you can omit or not write it, so that the error message can be written to Chinese directly)

1 val.age.message=\u5E74\u9F84\u4E0D\u80FD\u8D85\u8FC720\u5C812 3 username.not.null=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A4 pwd.not.null=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A5 username.length=\u7528\u6237\u540D\u6700\u5927\u4E0D\u80FD\u8D85\u8FC7{max},\u6700\u5C0F\u4E0D\u80FD\u5C11\u4E8E{min}6 7 email.format.error=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E

 

Verified bean:

1 package com. lee. web. entity; 2 3 import javax. validation. constraints. max; 4 import javax. validation. constraints. pattern; 5 6 import org. hibernate. validator. constraints. email; 7 import org. hibernate. validator. constraints. length; 8 import org. hibernate. validator. constraints. notBlank; 9 10 public class ValBean {11 12 13/** 14 * built-in constraint 15 * @ Null annotation element must be null 16 * @ NotNull The annotated element must not be null 17 * @ AssertTrue the annotated element must be true 18 * @ AssertFalse the annotated element must be false 19 * @ Min (value) the element to be commented must be a number and its value must be greater than or equal to the specified minimum value. 20 * @ Max (value) the element to be commented must be a number, the value must be smaller than or equal to the specified maximum value 21 * @ DecimalMin (value) The annotated element must be a number and its value must be greater than or equal to the specified minimum value 22 * @ DecimalMax (value) the annotated element must be a number whose value must be less than or equal to the specified maximum value 23 * @ Size (max =, min =) the size of the element to be commented must be within the specified range of 24 * @ Digits (integer, fraction) the element to be commented must be a number, the value must be within the acceptable range of 25 * @ Past annotated Elements It must be a past date 26 * @ Future the annotated element must be a Future date 27 * @ Pattern (regex =, flag =) the annotated element must comply with the specified regular expression 28 * Hibernate Validator appended constraint 29 * @ NotBlank (message =) to verify that the string is not null, and the Length must be greater than 0 30 * @ Email the annotated element must be Email address 31 * @ Length (min =, max =) the size of the commented string must be within the specified Range 32 * @ NotEmpty the commented string must be non-null 33 * @ Range (min =, max =, message =) the annotated element must be 34 */35 private Long id in the appropriate range; 36 37 @ Max (value = 20, message = "{val. age. message} ") 38 Private Integer age; 39 40 @ NotBlank (message = "{username. not. null} ") 41 @ Length (max = 6, min = 3, message =" {username. length} ") 42 private String username; 43 44 @ NotBlank (message =" {pwd. not. null} ") 45 @ Pattern (regexp ="/^ (?! [0-9] + $ )(?! [A-zA-Z] + $) [0-9A-Za-z] {6, 10} $/", message =" the password must be 6 ~ Combination of 10 digits and letters ") 46 private String password; 47 48 49 @ Pattern (regexp =" ^ (13 [0-9]) | (15 [^ 4, \ D]) | (18 [-9]) \ d {8} $ ", message =" Incorrect Mobile phone Number Format ") 50 private String phone; 51 52 @ Email (message = "{email. format. error} ") 53 private String email; 54 55 public Long getId () {56 return id; 57} 58 59 public void setId (Long id) {60 this. id = id; 61} 62 63 public String getUsername () {64 return username; 65} 66 67 public void setUsername (String username) {68 this. username = username; 69} 70 71 public String getPassword () {72 return password; 73} 74 75 public void setPassword (String password) {76 this. password = password; 77} 78 79 public String getPhone () {80 return phone; 81} 82 83 public void setPhone (String phone) {84 this. phone = phone; 85} 86 87 public String getEmail () {88 return email; 89} 90 91 public void setEmail (String email) {92 this. email = email; 93} 94 95 public Integer getAge () {96 return age; 97} 98 99 public void setAge (Integer age) {100 this. age = age, 101} 102}

Controller, json form, or rest interface.

1 @ RequestMapping (value = "/val", method = RequestMethod. POST) 2 @ ResponseBody 3 public LeeJSONResult val (@ Valid @ RequestBody ValBean, BindingResult result) throws Exception {4 5 if (result. hasErrors () {6 // if it fails, the jump prompt is 7 Map <String, String> map = getErrors (result); 8 return LeeJSONResult. error (map); 9} else {10 // continue business logic 11} 12 13 return LeeJSONResult. OK (); 14} 15 16 private Map <String, String> getErrors (BindingResult result) {17 Map <String, String> map = new HashMap <String, String> (); 18 List <FieldError> list = result. getFieldErrors (); 19 for (FieldError error: list) {20 System. out. println ("error. getField (): "+ error. getField (); 21 System. out. println ("error. getdefamessage message (): "+ error. getdefamessage message (); 22 23 map. put (error. getField (), error. getdefamessage message (); 24} 25 return map; 26}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.