Hibernate验证信息
- 最新版本需要自己添加依赖 Spring中只有判断空的校验
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
public class UsersBo {
@NotBlank(message = "用户名不能为空")
@Length(max = 12,message = "用户名不能超过12位")
@ApiModelProperty(value = "用户名",example = "张三",required = true)
private String username;
// @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$",message = "密码必须由8到16位大小写字母、数字组成且第一位必须是字母")
@ApiModelProperty(value = "密码(注册无需前端加密, 登录前端加密)",example = "123456",required = true)
private String password;
}
@PostMapping("login")
public Result doLogin(@RequestBody @Valid UsersBo usersBo,
BindingResult bindingResult,
HttpServletRequest request,
HttpServletResponse response){
if(bindingResult.hasErrors()){
Map<String,String> map = new HashMap<>();
for (FieldError error: bindingResult.getFieldErrors()) {
String errorField = error.getField();
String errorMsg = error.getDefaultMessage();
map.put(errorField,errorMsg);
}
return Result.error(map);
}
Users users = usersService.doLogin(usersBo);
if (users == null){
return Result.error(CodeMsg.USERNAME_PWD_ERROR);
}
CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(users),true);
return Result.success(users);
}