springMVC validator参数校验最新版
2020-05-23 本文已影响0人
ColorsLee
1.首先导包,这里需要导入两个jar 包,只导入一个会报错。
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>3.0.3</version>
</dependency>
2.新建实体类Student,在其中使用校验注解
public class Student implements Serializable{
@NotEmpty(message = "用户名不可为空")
String name;
String address;
@Email(message = "邮箱格式不真该")
String email;
@Max(100)@Min(1)
int age;
@Null
String sex;
@Min(value = 1,message = "不可是空")
float score;
@Size(message = "位不对",max = 11,min = 11)
String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", score=" + score +
", phone='" + phone + '\'' +
'}';
}
}
3.新建controller测试,接收数据,其中@Valid注解表示对该对象启用校验,不可缺少。BindingResult是校验的结果,我们可以通过结果来判断给前端返回什么数据(如用户名为空,邮箱格式不对)
@Controller
public class TestController {
@ResponseBody
@RequestMapping("test")
public String test(@Valid Student student, BindingResult result){
List<ObjectError> errors = result.getAllErrors();
for (ObjectError e : errors) {
System.out.println(e.getDefaultMessage());
}
if (errors.size()==0){
return "成功";
}else {
return "有格式不正确的参数";
}
}
}
4.网页测试文件也贴出来
<body>
<button id="b">button</button>
<script src="js/jquery-1.8.3.min.js"></script>
<script>
$("#b").click(function () {
$.ajax({
url:"test",
type:"post",
data:{
name:"张三",
age:12,
address:"天津",
score:12.6,
email:"hello@11.com",
phone:"29438489349"
},
success:function (result) {
window.alert(result)
}
})
})
</script>
</body>
5.其他文件不需要需改,不需要修改配置文件等,以上就是全部,亲测无误。