欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

Spring中的WebDataBinder如何使用?

程序员文章站 2022-04-19 14:26:07
...
还是老规矩,开门见山。 我们开发的时候经常会从html,jsp中将参数传到后台,可是经常会遇到的一种情况就是传过来的数据到后台要组装成一种对象的格式,最常见的就是enum类型了。这时候spring提供的@initBinder这个annotation 就发挥了很大的作用。

   下面一个例子,我们创建一个JavaBean(username, password, email and date of birth of a user),我们创建两个自定义的验证类.第一个,我们验证用户名和密码.第二个,验证邮箱,

在Eclipse中Demo的结构

Spring中的WebDataBinder如何使用?

Spring中的WebDataBinder如何使用?

Validator 是一个有两个方法的接口;
boolean supports(Class<?> clazz) : 检验参数是否验证成功的实例类;
void validate(Object target, Errors errors) : 如果 supports() 方法返回真, target object 合法. Errors.rejectValue() 方法用一个字段名注册错误信息;

Uservalidator.java
Spring中的WebDataBinder如何使用?Spring中的WebDataBinder如何使用?
 1 package com.concretepage.validators; 2 import org.springframework.stereotype.Component; 3 import org.springframework.validation.Errors; 4 import org.springframework.validation.ValidationUtils; 5 import org.springframework.validation.Validator; 6 import com.concretepage.User; 7 @Component 8 public class UserValidator implements Validator  { 9     @Override10     public boolean supports(Class<?> clazz) {11         return User.class.isAssignableFrom(clazz);12     }13     @Override14     public void validate(Object target, Errors errors) {15         User user = (User)target;16         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "","Username is empty");17         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "", "Password is empty");18         if (user.getName().length()<5) {19             errors.rejectValue("name","", "Username length is less than 5");20         }21     }22 }
UserValidator.java
EmailValidator.java
Spring中的WebDataBinder如何使用?Spring中的WebDataBinder如何使用?
 1 package com.concretepage.validators; 2 import org.springframework.stereotype.Component; 3 import org.springframework.validation.Errors; 4 import org.springframework.validation.ValidationUtils; 5 import org.springframework.validation.Validator; 6 import com.concretepage.User; 7 @Component 8 public class EmailValidator implements Validator { 9     @Override10     public boolean supports(Class<?> clazz) {11         return User.class.isAssignableFrom(clazz);12     }13     @Override14     public void validate(Object target, Errors errors) {15         User user = (User)target;16         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "","Email is empty");17         if (!user.getEmail().contains("@")) {18             errors.rejectValue("email","", "Email is not valid.");19         }20     }21 }
EmailValidator.java
User.java
Spring中的WebDataBinder如何使用?Spring中的WebDataBinder如何使用?
 1 package com.concretepage;
 2 import java.util.Date;
 3 public class User {
 4     private String name;
 5     private String password;
 6     private String email;
 7     private Date dob;
 8     public String getName() {
 9         return name;
10     }
11     public void setName(String name) {
12         this.name = name;
13     }
14     public String getPassword() {
15         return password;
16     }
17     public void setPassword(String password) {
18         this.password = password;
19     }
20     public String getEmail() {
21         return email;
22     }
23     public void setEmail(String email) {
24         this.email = email;
25     }
26     public Date getDob() {
27         return dob;
28     }
29     public void setDob(Date dob) {
30         this.dob = dob;
31     }
32 }
User.java
MyWorldController
Spring中的WebDataBinder如何使用?Spring中的WebDataBinder如何使用?
 1 package com.concretepage; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4  5 import javax.validation.Valid; 6  7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.beans.propertyeditors.CustomDateEditor; 9 import org.springframework.stereotype.Controller;10 import org.springframework.ui.ModelMap;11 import org.springframework.validation.BindingResult;12 import org.springframework.web.bind.WebDataBinder;13 import org.springframework.web.bind.annotation.InitBinder;14 import org.springframework.web.bind.annotation.ModelAttribute;15 import org.springframework.web.bind.annotation.RequestMapping;16 import org.springframework.web.bind.annotation.RequestMethod;17 import org.springframework.web.servlet.ModelAndView;18 19 import com.concretepage.validators.EmailValidator;20 import com.concretepage.validators.UserValidator;21 @Controller22 @RequestMapping("/myworld")23 public class MyWorldController {24     @Autowired25     private UserValidator userValidator;26     @Autowired27     private EmailValidator emailValidator;28 29     @RequestMapping(value="signup", method = RequestMethod.GET)30     public ModelAndView user(){31         return new ModelAndView("user","user",new User());32     }33     @InitBinder34     public void dataBinding(WebDataBinder binder) {35         binder.addValidators(userValidator, emailValidator);36         SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");37         dateFormat.setLenient(false);38         binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));39     }40     41     @RequestMapping(value="save", method = RequestMethod.POST)42     public String createUser(@ModelAttribute("user") @Valid User user,BindingResult result, ModelMap model) {43         if(result.hasErrors()) {44             return "user";45         }46         System.out.println("Name:"+ user.getName());47         System.out.println("Email:"+ user.getEmail());48         System.out.println("Date of Birth:"+ user.getDob());49         model.addAttribute("msg", "Welcome to My World!");50         return "success";51     }    
52 }
MyWorldController
页面表单
Spring中的WebDataBinder如何使用?Spring中的WebDataBinder如何使用?
  <form:form action="save" method="post" commandName="user"><tr>  <td>User Name:</td> <td><form:input  path="name"/> </td> 
          <td> <form:errors path="name" cssStyle="color: red;"/></td> </tr><tr> <td> Password :</td> <td><form:input path="password"/> </td> 
         <td> <form:errors path="password" cssStyle="color: red;"/> </td> </tr><tr> <td>  Email :</td> <td><form:input path="email"/> </td> 
         <td> <form:errors path="email" cssStyle="color: red;"/> </td> </tr><tr> <td>  Date of Birth :</td> <td><form:input path="dob"/> </td> 
         <td> <form:errors path="dob" cssStyle="color: red;"/> </td> </tr>         <tr> <td colspan=3>   <input type="submit"> </td>
  </form:form>

以上就是Spring中的WebDataBinder如何使用?的详细内容,更多请关注其它相关文章!