spring mvc 能很方便的使用javax 的验证api @valid
在方法类中配置校验属性
<\code>
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Spitter{
private String firstName;
private String lastName;
@NotNull
@Size(min = 2, max = 50)
private String username;
@NotNull
private String password;
//省略set,get
}
</\code>
然后在Controller里启用
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String processRegistration(
@Valid Spitter spitter,Errors errors
){
if(errors.hasErrors()){
System.out.println(errors.toString());
return "registerForm";
}
repository.addSpitter(spitter);
return "redirect:/homepage";
}
注意,需要hibernate-validator的类库,否则不启用,也不报错.