之前的逻辑:
- 由@InitBinder表示的方法,可以对WebDataBinder对象进行初始化。WebDataBinder是DataBinder的子类,用于完成由表单到JavaBean属性的绑定。
- @InitBinder方法不能有返回值,它必须声明为void。
- @InitBinder方法的参数通常是WebDataBinder
- @InitBinder可以对WebDataBinder进行初始化。
新增后的校验:
修改后:
CityRequestValidator类:
package org.spring.springboot.controller;
import org.apache.commons.lang3.StringUtils;
import org.spring.springboot.domain.City;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* 新建城市校验器
**/
public class CityRequestValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return City.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "provinceId", "provinceId 省份编号不能为空");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cityName", "cityName 城市名称不能为空");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "description 描述不能为空");
City city = (City) target;
if (!RegexUtils.checkMySqlDefaultSupportCharacter(city.getProvinceId().toString())) {
errors.rejectValue("provinceId", "省份编号存在非法字符,请重新输入");
}
if (!RegexUtils.checkYtxUsername(city.getCityName(), 2, 15)) {
errors.rejectValue("cityName", "城市名称过长,请重新输入");
}
if (StringUtils.isBlank(city.getDescription())) {
errors.rejectValue("description", "描述不能为空,请重新输入");
}
}
}
package org.spring.springboot.domain;
import java.io.Serializable;
/**
* 城市实体类
*
* Created by bysocket on 07/02/2017.
*/
public class City implements Serializable {
private static final long serialVersionUID = -1L;
/**
* 城市编号
*/
private Long id;
/**
* 省份编号
*/
private Long provinceId;
/**
* 城市名称
*/
private String cityName;
/**
* 描述
*/
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProvinceId() {
return provinceId;
}
public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "City{" +
"id=" + id +
", provinceId=" + provinceId +
", cityName='" + cityName + '\'' +
", description='" + description + '\'' +
'}';
}
}