@valid

作者: KingSun_阳 | 来源:发表于2016-12-02 15:45 被阅读0次

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的类库,否则不启用,也不报错.

相关文章

网友评论

      本文标题:@valid

      本文链接:https://www.haomeiwen.com/subject/pemjhttx.html