实体类Person.java(在属性或get方法上加注解)
package com.luohao.entity;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
public class Person {
@Pattern(regexp="^\\w{6,10}$",message="用户名必须是字母")
private String userName;
@Length(min=6,max=20,message="密码必须是6-20位")
private String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
controller中的java类
@RequestMapping("/login")
public ModelAndView login(@Valid @ModelAttribute("person") Person person,BindingResult bindingResult) {
//如果参数和表单的name相同就不用注解表明这是参数
if (bindingResult.hasErrors()) {
ModelAndView mav = new ModelAndView();
Map<String,Object> map = new HashMap<String, Object>();
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError err : errors) {
map.put(err.getField(), err.getDefaultMessage());
}
mav.addObject("fieldErrors",map);
mav.setViewName("../login.jsp");
return mav;
}else {
return new ModelAndView("../index.jsp") ;
}
}
![]()
jsp页面
<body>
<form action="home/login.do" method="post">
用户名:<input type="text" name = "userName" />
${fieldErrors["userName"]}<br>
密 码:<input type="password" name = "passWord" />
${fieldErrors["passWord"]}<br>
<input type="submit" value="提交" />
</form>
</body>
需要用到的数据验证包: