Spring中WebDataBinder使用详解

发布时间:2020-09-17 10:57:04 作者:无名小卒升级中
来源:脚本之家 阅读:195

Spring MVC Validator @InitBinder and WebDataBinder;Validator是一个用来我们自定义验证的sping接口,WebDataBinder 绑定你的自定义参数,你直接在你的控制器类中通过@InitBinder 注解的方式配置 Web 数据绑定.registerCustomEditor()是一个属性编辑器,比如自定义的日期编辑它绑定web请求参数到JavaBean的属性;

下面一个例子,我们创建一个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

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页面表单

<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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. spring data jpa使用详解
  2. 详解Spring Boot如何使用多线程

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring webdatabinder dat

上一篇:jsp如何实现背景渐变色

下一篇:php ltrim函数的使用方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》