spring boot的表单验证

157 篇文章 16 订阅

一.常用验证规则

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

二.案例:新建项目:05-spt-form-check-01

1.pom文件:

    <!-- springBoot的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.0.1.RELEASE</version>
    </dependency>
    <!-- thymeleaf的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      <version>2.0.1.RELEASE</version>
    </dependency>

2.后端代码:

package com.ljf.form.controller;

import com.ljf.form.model.Users;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

/**
 * @ClassName: UsersController
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2020/07/28 21:04:26
 * @Version: V1.0
 **/
@Controller
public class UsersController {
    @RequestMapping("/addUser")
   // public String showPage(){
    public String showPage(@ModelAttribute("aa")  Users users){
        return "add";
    }

    /**
     * 完成用户添加
     *@Valid 开启对Users对象的数据校验
     *BindingResult:封装了校验的结果
     */
    @RequestMapping("/save")
   // public String saveUser(@Valid Users users, BindingResult result){
    public String saveUser(@ModelAttribute("aa") @Valid Users users, BindingResult result){
        if(result.hasErrors()){
            return "add";
        }
        System.out.println(users);
        return "ok";
    }
}

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/><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>
	-->
<!---  使用别名aa --->
	<form th:action="@{/save}" method="post">
		用户姓名:<input type="text" name="name" /><font color="red" th:errors="${aa.name}"></font><br/><br/>
		用户密码:<input type="password" name="password" /><font color="red" th:errors="${aa.password}"></font><br/>
		用户年龄:<input type="text" name="age" /><font color="red" th:errors="${aa.age}"></font><br/>
		<input type="submit" value="OK"/>
	</form>
</body>
</html>

4.结构调用:

访问: http://localhost:8081/addUser 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值