Spring中WebDataBinder使用詳解
Spring MVC Validator @InitBinder and WebDataBinder;Validator是一個(gè)用來(lái)我們自定義驗(yàn)證的sping接口,WebDataBinder 綁定你的自定義參數(shù),你直接在你的控制器類(lèi)中通過(guò)@InitBinder 注解的方式配置 Web 數(shù)據(jù)綁定.registerCustomEditor()是一個(gè)屬性編輯器,比如自定義的日期編輯它綁定web請(qǐng)求參數(shù)到JavaBean的屬性;
下面一個(gè)例子,我們創(chuàng)建一個(gè)JavaBean(username, password, email and date of birth of a user),我們創(chuàng)建兩個(gè)自定義的驗(yàn)證類(lèi).第一個(gè),我們驗(yàn)證用戶(hù)名和密碼.第二個(gè),驗(yàn)證郵箱,
在Eclipse中Demo的結(jié)構(gòu)


Validator 是一個(gè)有兩個(gè)方法的接口;
boolean supports(Class<?> clazz) : 檢驗(yàn)參數(shù)是否驗(yàn)證成功的實(shí)例類(lèi);
void validate(Object target, Errors errors) : 如果 supports() 方法返回真, target object 合法. Errors.rejectValue() 方法用一個(gè)字段名注冊(cè)錯(cuò)誤信息;
UserValidator.java
package com.concretepage.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.concretepage.User;
@Component
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User)target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "","Username is empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "", "Password is empty");
if (user.getName().length()<5) {
errors.rejectValue("name","", "Username length is less than 5");
}
}
}
EmailValidator.java
package com.concretepage.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.concretepage.User;
@Component
public class EmailValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User)target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "","Email is empty");
if (!user.getEmail().contains("@")) {
errors.rejectValue("email","", "Email is not valid.");
}
}
}
User.java
package com.concretepage;
import java.util.Date;
public class User {
private String name;
private String password;
private String email;
private Date dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
MyWorldController
package com.concretepage;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.concretepage.validators.EmailValidator;
import com.concretepage.validators.UserValidator;
@Controller
@RequestMapping("/myworld")
public class MyWorldController {
@Autowired
private UserValidator userValidator;
@Autowired
private EmailValidator emailValidator;
@RequestMapping(value="signup", method = RequestMethod.GET)
public ModelAndView user(){
return new ModelAndView("user","user",new User());
}
@InitBinder
public void dataBinding(WebDataBinder binder) {
binder.addValidators(userValidator, emailValidator);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
}
@RequestMapping(value="save", method = RequestMethod.POST)
public String createUser(@ModelAttribute("user") @Valid User user,BindingResult result, ModelMap model) {
if(result.hasErrors()) {
return "user";
}
System.out.println("Name:"+ user.getName());
System.out.println("Email:"+ user.getEmail());
System.out.println("Date of Birth:"+ user.getDob());
model.addAttribute("msg", "Welcome to My World!");
return "success";
}
}
Form頁(yè)面表單
<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>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring中@RestControllerAdvice注解的使用詳解
這篇文章主要介紹了Spring中@RestControllerAdvice注解的使用詳解,@RestControllerAdvice是一個(gè)組合注解,由@ControllerAdvice、@ResponseBody組成,而@ControllerAdvice繼承了@Component,需要的朋友可以參考下2024-01-01
MybatisPlus關(guān)聯(lián)查詢(xún)的完美實(shí)現(xiàn)方案
我們?cè)陧?xiàng)目開(kāi)發(fā)的時(shí)候,難免會(huì)遇到連表查詢(xún)的操作,所以下面這篇文章主要給大家介紹了關(guān)于MybatisPlus關(guān)聯(lián)查詢(xún)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-12-12
Java語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單FTP軟件 FTP連接管理模塊實(shí)現(xiàn)(8)
這篇文章主要為大家詳細(xì)介紹了Java語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單FTP軟件,F(xiàn)TP連接管理模塊的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
Python文件高級(jí)操作函數(shù)之文件信息獲取與目錄操作
這篇文章主要介紹了Python文件高級(jí)操作函數(shù)之文件信息獲取與目錄操作,在Python中,內(nèi)置了文件(File)對(duì)象。在使用文件對(duì)象時(shí),首先需要通過(guò)內(nèi)置的open()方法創(chuàng)建一個(gè)文件對(duì)象,然后通過(guò)該對(duì)象提供的方法進(jìn)行一些基本文件操作,需要的朋友可以參考下2023-05-05
Java多線(xiàn)程之FutureTask的介紹及使用
之前介紹了線(xiàn)程池相關(guān)的對(duì)象,Runable Callable與Future,下面介紹FutureTask的作用,它的特性是怎樣的呢,需要的朋友可以參考下2021-06-06
SpringBoot的Admin服務(wù)監(jiān)控詳解
這篇文章主要介紹了SpringBoot的Admin服務(wù)監(jiān)控詳解,Spring Boot Admin(SBA)是一個(gè)開(kāi)源的社區(qū)項(xiàng)目,用于管理和監(jiān)控 Spring Boot 應(yīng)用程序,需要的朋友可以參考下2024-01-01
Java Web十條開(kāi)發(fā)實(shí)用小知識(shí)
這篇文章主要介紹了Java Web十條開(kāi)發(fā)實(shí)用小知識(shí)的相關(guān)資料,需要的朋友可以參考下2016-05-05
Hibernate一對(duì)多關(guān)聯(lián)雙向關(guān)聯(lián)代碼實(shí)現(xiàn)分享
Hibernate一對(duì)多關(guān)聯(lián)雙向關(guān)聯(lián)代碼實(shí)現(xiàn)分享,大家參考使用吧2013-12-12

