org.hibernate
hibernate-validator
6.0.4.Final
package com.springboot.entity;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -7362371894429216969L;
@NotEmpty(message="用户名不能为空")
@Length(min=6,max = 12,message="用户名长度必须位于6到12之间")
private String userName;
@NotEmpty(message="密码不能为空")
@Length(min=6,message="密码长度不能小于6位")
private String passWord;
@Email(message="邮箱格式错误")
private String email;
@Pattern(regexp = "^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message = "身份证格式错误")
private String idCard;
@Pattern(regexp = "^((13[0-9]{1})|159|153)+\\d{8}$",message = "手机号格式错误")
private String phone;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public User(@NotEmpty(message = "用户名不能为空") @Length(min = 6, max = 12, message = "用户名长度必须位于6到12之间") String userName, @NotEmpty(message = "密码不能为空") @Length(min = 6, message = "密码长度不能小于6位") String passWord, @Email(message = "请输入正确的邮箱") String email, @Pattern(regexp = "^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message = "身份证格式错误") String idCard, @Pattern(regexp = "^((13[0-9]{1})|159|153)+\\d{8}$", message = "手机号格式错误") String phone) {
this.userName = userName;
this.passWord = passWord;
this.email = email;
this.idCard = idCard;
this.phone = phone;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", email='" + email + '\'' +
", idCard='" + idCard + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
package com.springboot.controller;
import com.springboot.entity.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
public class TestController {
@PostMapping("/test")
public String testDemo(@Valid User user, BindingResult bindingResult){
System.out.println(user.toString());
StringBuffer stringBuffer = new StringBuffer();
if(bindingResult.hasErrors()){
List list =bindingResult.getAllErrors();
for (ObjectError objectError:list) {
stringBuffer.append(objectError.getDefaultMessage());
stringBuffer.append("---");
}
}
return stringBuffer!= null ?stringBuffer.toString():"";
}
}
作为测试demo,到这里就可以直接测试了
@NotNull、@NotEmpty 和 @NotBlank 都是用于Java中进行参数校验的注解,它们之间的区别如下:
@NotNull 注解用于限制参数不能为null。
@NotEmpty 注解用于限制字符串、集合、Map等不能为null且大小必须大于0。
@NotBlank 注解用于限制字符串不能为null并且去除两端空格后长度必须大于0。
可以简单理解为:
需要注意的是,这三个注解都只能用于校验方法参数,不能用于校验类属性。同时,它们都属于Hibernate Validator提供的校验注解,如果要使用这些注解,需要引入Hibernate Validator的相关依赖。
要看清楚,用那种方法,具体导入什么依赖
org.springframework.boot
spring-boot-starter-validation
这种情况主要是应对有一些特殊场景,没有相应的注解进行校验,当然,在service层中去写相应的逻辑也行,这里算是提供另一个思路和方法(说白了就是写一个自定义注解,在自定义注解中写上相应的要判断的逻辑)
import com.example.demo.MyConstraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class MyConstraintValidator implements ConstraintValidator {
//String为校验的类型
@Override
public void initialize(MyConstraint myConstraint) {
//启动时执行
}
/**
* @Description: 自定义校验逻辑
*/
@Override
public boolean isValid(String s, ConstraintValidatorContext validatorContext) {
if (!(s.equals("北京") || s.equals("上海"))) {
return false;
}
return true;
}
}
import com.example.MyConstraintValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//用于指定使用范围,该处限定只能在字段上使用
@Target({ElementType.FIELD})
//表示注解在运行时可以通过反射获取到
@Retention(RetentionPolicy.RUNTIME)
//@Constraint注解,里面传入了一个validatedBy的字段,指定该注解校验逻辑
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
/**
* @Description: 错误提示
*/
String message() default "请输入中国政治或者经济中心的城市名";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
import com.example.demo.MyConstraint;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.io.Serializable;
@Data
public class User implements Serializable {
/**
* 主键ID
*/
private Long id;
@NotBlank(message = "用户名不能为空")
@Length(min = 5, max = 20, message = "用户名长度为5-20个字符")
private String name;
@NotNull(message = "年龄不能为空")
@Min(value = 18 ,message = "最小18岁")
@Max(value = 60,message = "最大60岁")
private Integer age;
/* @NotBlank(message = "电话不可以为空")
@Length(min = 1, max = 13, message = "电话长度需要在13个字符以内")
private String phone;*/
@Email(message = "请输入邮箱")
@NotBlank(message = "邮箱不能为空")
private String email;
/* @NotNull(message = "必须指定用户状态")
@Min(value = 0, message = "用户状态不合法")
@Max(value = 1, message = "用户状态不合法")
private Integer status;*/
@MyConstraint
private String answer;
}
import com.example.demo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
@Controller
public class TestValidator {
@GetMapping("/test")
public String showForm(User user) {
return "form";
}
@GetMapping("/results")
public String results() {
return "results";
}
@PostMapping("/test")
public String checkUser(@Valid User user, BindingResult bindingResult, RedirectAttributes attr) {
//特别注意实体中的属性必须都验证过了,不然不会成功
if (bindingResult.hasErrors()) {
return "form";
}
/**
* @Description:
* 1.使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面 ,如上代码即为?name=long&age=45
* 2.使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,待重定向url获取该参数后从session中移除,
* 这里的redirect必须是方法映射路径。你会发现redirect后的值只会出现一次,刷新后不会出现了,对于重复提交可以使用此来完成。
*/
attr.addFlashAttribute("user", user);
return "redirect:/results";
}
}