5.SpringBoot之服务端表单数据校验

本文介绍如何在SpringBoot中使用Hibernate-validate框架对表单数据进行校验,包括在实体类中添加校验规则、在Controller中开启校验及在页面中显示错误信息的方法。同时,列举了多种校验注解如@NotBlank、@NotEmpty、@Length等的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.SpringBoot 对表单做数据校验

1.1SpringBoot 对表单数据校验的技术特点

SpringBoot 中使用了 Hibernate-validate 校验框架

1.2SpringBoot 表单数据校验步骤

1.2.1在实体类中添加校验规则
public class Users {
@NotBlank //非空校验
private String name;
@NotBlank //密码非空校验
private String password;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Users [name=" + name + ", password=" + password + ", age="
+ age + "]";
}
}
1.2.2在 Controller 中开启校验
/**
* 完成用户添加
*@Valid 开启对 Users 对象的数据校验
*BindingResult:封装了校验的结果
*/
@RequestMapping("/save")
public String saveUser(@Valid Users users,BindingResult result){
if(result.hasErrors()){
return "add";
}
System.out.println(users);
return "ok";
}

1.2.3在页面中获取提示信息
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<form th:action="@{/save}" method="post">
用户姓名:<input type="text" name="name"/><font color="red"
th:errors="${users.name}"></font><br/>
用户密码:<input type="password" name="password" /><font
color="red" th:errors="${users.password}"></font><br/>
用户年龄:<input type="text" name="age" /><font color="red"
th:errors="${users.age}"></font><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>

2.其他校验规则

@NotBlank: 判断字符串是否为 null 或者是空串(去掉首尾空格)。
@NotEmpty: 判断字符串是否 null 或者是空串。
@Length: 判断字符的长度(最大或者最小)
@Min: 判断数值最小值
@Max: 判断数值最大值
@Email: 判断邮箱是否合法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值