在Spring 3 中,对表单提交的校验方式比较常见的有两种
(1)基于注解:对于简单的属性校验,例如,长度,非空等,可以使用Spring,或是Hibernate自带的校验注解
(2)自定义校验类:对于复杂的业务校验可以自定义校验类,该类继承自org.springframework.validation.Validator
(3)前台JS校验
增加表单校验功能大概分一下几个步骤
只需要在相关的实体字段上添加校验注解即可,下面的例子基于hibernate的校验标签
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Email; public class User extends BasePO { private static final long serialVersionUID = 6295814719063548261L; private Long id; @Length(min = 3, max = 20) private String name; @Length(min = 6, max = 20) private String pwd; @Email private String email; /*get set 省略*/
创建基于org.springframework.validation.Validator的子类,实现supports,validate方法
import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.eric.User; public class UserValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return User.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; if (!user.getPwd().equals(user.getRetryPwd())) { errors.rejectValue("retryPwd", "error.pwd.notmath"); } } }
<mvc:annotation-driven/>
需要在Spring MVC Controller中添加以下方法
@InitBinder protected void initBinder(WebDataBinder binder) { binder.addValidators(new UserValidator()); }
不管是自定义校验,还是基于注解的校验,在使用的方式上没有区别,都需要经过下面两步
(1)在Controller 方法中添加@Valid注解
当方法的参数中使用@Valid注解时,进入该方法时会对传进来的user参数进行校验,校验的结果存储在result中,可以在方法中对result.hasErrors()的状态进行判断
@RequestMapping(USER_UPDATE_URL) public String action(@Valid User user, BindingResult result, @RequestParam(value = "action") String action, Map<String, Object> model) { String resultURL = null; if (result.hasErrors()) { prepareUpdate(model, user); return USER_CREATE_URL; } return resultURL; }
(2)在页面中添加错误标签
<sf:errors path="retryPwd" cssClass="error"/> 中的path指定了对应的属性路径
<div class="form-group"> <label for="password"><spring:message code="user.field.pwd" /></label> <sf:password path="pwd" id="pwd" class="form-control" size="15" showPassword="true" maxlength="50" /> <sf:errors path="pwd" cssClass="error" /> </div> <div class="form-group"> <label for="confirmpassword"><spring:message code="user.field.repwd" /></label> <sf:password path="retryPwd" id="retrypwd" class="form-control" size="15" maxlength="50" showPassword="true" /> <sf:errors path="retryPwd" cssClass="error" /> </div>
程序员如何做SOHO一族接单赚外快呢?,布布扣,bubuko.com
原文:http://blog.csdn.net/q969403688/article/details/28404183