Validator +BindResult 进行校验
@NotNull:不能为null,但可以为empty
@NotEmpty:不能为null,而且长度必须大于0
@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0
@Data
@Entity
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "User Entity", description = "User Entity")
public class User extends BaseEntity {
@Column
@NotEmpty(message = "用户工号不能为空")
@ApiModelProperty(value = "工号", example = "680059")
private String userCode;
@Column
@NotNull(message = "用户姓名不能为空")
@Size(min = 6, max = 12, message = "用户姓名必须是6-12个字符")
@ApiModelProperty(value = "姓名", example = "马颖华")
private String userName;
@Column
@ApiModelProperty(value = "密码", example = "123456")
private String password;
}
接口需要校验的参数上加上@Valid注解,当请求参数传递到接口的时候Validator就自动完成校验了,校验的结果就会封装到BindingResult中去,如果有错误信息我们直接返回给前端
@PostMapping("/add")
@ApiOperation(value = "add User", notes = "add User")
public String add(Model model, @Valid User user, BindingResult bindingResult) {
// 判断是否含有校验不匹配的参数错误
if (bindingResult.hasErrors()) {
// 获取所有字段参数不匹配的参数集合
List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
Map<String, Object> result = new HashMap<>(fieldErrorList.size());
fieldErrorList.forEach(error -> {
// 将错误参数名称和参数错误原因存于map集合中
result.put(error.getField(), error.getDefaultMessage());
});
model.addAttribute("errors", result);
return PARAM_ERROR;
}
userService.save(user);
return REDIRECT;
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/header::layout(~{::title})">
<title>参数错误</title>
</head>
<body>
<h3>对不起,提交参数不符合要求!</h3>
<table class="table table-striped projects">
<tr th:each="item,userStat:${errors}">
<td th:text="${userStat.index}+1"></td>
<td th:text="${userStat.current.key}"></td><!-- key-->
<td th:text="${userStat.current.value}"></td><!-- value-->
</tr>
</table>
<a href="/index">返回首页</a>
</body>
</html>
全局异常处理
GlobalExceptionHandler
/**
* @author Moses
* @date 2020/7/2
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 参数校验异常
* @param model
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public String BindExceptionHandler(Model model, BindException e) {
// 获取所有字段参数不匹配的参数集合
List<FieldError> fieldErrorList = e.getFieldErrors();
Map<String, Object> result = new HashMap<>(fieldErrorList.size());
fieldErrorList.forEach(error -> {
// 将错误参数名称和参数错误原因存于map集合中
result.put(error.getField(), error.getDefaultMessage());
});
model.addAttribute("errors", result);
return "error/412";
}
}
@PostMapping("/add")
@ApiOperation(value = "add User", notes = "add User")
public String add(@Valid User user) {
userService.save(user);
return REDIRECT;
}
前端校验
<script th:src="@{/common/plugins/jquery-validation-1.19.2/jquery.validate.min.js}"></script>
<script th:src="@{/common/plugins/jquery-validation-1.19.2/localization/messages_zh.js}"></script>
<div class="card-body">
<div class="form-group">
<label>工号</label>
<input type="text" class="form-control" placeholder="请输入 ..." name="userCode" required/>
</div>
<div class="form-group">
<label>姓名</label>
<input type="text" class="form-control" placeholder="请输入 ..." name="userName" required
min="6" max="12"/>
</div>
</div>