JSR303后端校验(一)
JSR303后端校验(一)
(1)在pom文件中添加依赖
<!-- JSR303后端校验 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.16.Final</version> </dependency>
(2)在实体类中添加对应的校检规则
private Integer id; @NotEmpty(message = "用户名不能为空") @Pattern(regexp="^\\w{6,18}$",message="用户名必须由6到18位的数字字母或者下划线组成") private String name; @Length(min=6,max=32,message="密码必须为6到32位的字符串") private String password; @NotNull(message = "年龄不能为空") @Max(value = 110,message = "输入的年龄不合法") @Min(value=1,message = "输入的年龄不合法") private Integer age; @Pattern(regexp = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$",message = "邮箱格式不正确") private String email;
(3)在controller中使用校检规则
@RequestMapping("/addStudent") public String addStudent(@Valid Student student,BindingResult result,ModelMap map) { if(result.hasErrors()) { List<FieldError> errors = result.getFieldErrors(); for (FieldError fieldError : errors) { System.out.println(fieldError); System.out.println("字段:"+fieldError.getField()+",信息:"+fieldError.getDefaultMessage()); map.put(fieldError.getField(), fieldError.getDefaultMessage()); if(fieldError.getField().equals("name")) { map.put("name", fieldError.getDefaultMessage()); } if(fieldError.getField().equals("password")) { map.put("password", fieldError.getDefaultMessage()); } if(fieldError.getField().equals("age")) { map.put("age", fieldError.getDefaultMessage()); } if(fieldError.getField().equals("age")) { map.put("age", fieldError.getDefaultMessage()); } if(fieldError.getField().equals("email")) { map.put("email", fieldError.getDefaultMessage()); } } }else { studentService.addStudent(student); } return "student"; }
(4)页面提示
<form action="addStudent" method="get">
用户名:<input type="text" name="name"><span style="color:red">${name }</span><br>
密码:<input type="text" name="password"><span style="color:red">${password }</span><br>
年龄:<input type="text" name="age"><span style="color:red">${age }</span><br>
邮箱:<input type="text" name="email"><span style="color:red">${email }</span><br>
出生日期:<input type="date" name="borth"><br>
<input type="submit" value="提交">
</form>