springmvc校验表单

xiaoxiao2021-02-28  47

1.因为是在maven项目下,需要引入如下三个包

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.3.5.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.1.Final</version> </dependency>

2.springmvc的配置文件中,只需要写一句话

<mvc:annotation-driven/>

不需要再添加了。

3.Pojo中添加一些注解,比如@Past所选时间不能是将来的。

@Past @DateTimeFormat(pattern="yyyy-MM-dd") private Date becomeStudent; @NotNull private String username;

4.在控制层里的方法里要对加以判断的方法参数前面加上@Valid,而且方法里一定要有Error对象,那么它的子集BindingResult也是可以的:

@RequestMapping(value = "/add.do",method = RequestMethod.POST) public String add(@Valid Student student, BindingResult result,Model model, ModelMap modelMap){ if(result.getErrorCount()>0){ for(FieldError error : result.getFieldErrors()){ log.info(error.getField()+" "+error.getDefaultMessage() ); } } model.addAttribute(student); modelMap.put("stu",student); log.info(student.toString()); return "listStudent"; }

一定要写在@Valid后面,有几个待验证的参就出现几次BindResult.

JSR303的验证类型:

@Null              被注释的元素必须为 null @NotNull            被注释的元素必须不为 null @AssertTrue          被注释的元素必须为 true @AssertFalse          被注释的元素必须为 false @Min(value)          被注释的元素必须是一个数字,其值必须大于等于指定的最小值 @Max(value)        被注释的元素必须是一个数字,其值必须小于等于指定的最大值 @DecimalMin(value)      被注释的元素必须是一个数字,其值必须大于等于指定的最小值 @DecimalMax(value)      被注释的元素必须是一个数字,其值必须小于等于指定的最大值 @Size(max, min)      被注释的元素的大小必须在指定的范围内 @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内 @Past              被注释的元素必须是一个过去的日期 @Future             被注释的元素必须是一个将来的日期 @Pattern(value)        被注释的元素必须符合指定的正则表达式 //-----------------下面是hibernate-valitor新增加的 @Email              被注释的元素必须是电子邮箱地址 @Length             被注释的字符串的大小必须在指定的范围内 @NotEmpty            被注释的字符串的必须非空 @Range              被注释的元素必须在合适的范围内
转载请注明原文地址: https://www.6miu.com/read-84969.html

最新回复(0)