It’s still the same old rules, straight to the point. When we develop, we often pass parameters from html and jsp to the background. However, one situation we often encounter is that the passed data needs to be assembled into an object format in the background. The most common one is the enum type. At this time, the @initBinder annotation provided by spring plays a great role.
In the following example, we create a JavaBean (username, password, email and date of birth of a user), and we create two custom validation classes .The first one, we verify the user name and password. The second one, verify the email address,
Validator is an interface with two methods;
boolean supports( Class> clazz) : Instance class to check whether the parameters are successfully verified;
void validate(Object target, Errors errors) : If supports() method Return true, the target object is legal. Errors.rejectValue() The method registers error information with a field name;
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
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
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
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 Page Form
<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>
The above is the detailed content of How to use WebDataBinder in Spring?. For more information, please follow other related articles on the PHP Chinese website!