SpringBoot(五)服务端表单数据校验

本文介绍如何在SpringBoot项目中实现用户添加功能,并详细讲解了利用Hibernate-validate进行表单数据校验的步骤,包括实体类校验规则设置、Controller中校验开启及页面错误信息展示。

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

目录:

一、实现添加用户功能

1、创建项目

2、修改pom文件

3、编写添加用户功能

3.1、创建实体类

3.2、编写Controller

3.3、编写页面add.html,ok.html

二、SpringBoot对表单做数据校验

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

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

2、SpringBoot表单数据校验步骤

2.1、在实体类中添加校验规则

2.2、在Controller中开启校验

2.3、在页面中获取提示信息

2.4、遇到异常

三、解决数据校验时的异常问题

1、修改代码:

2、如果参数的名称需要做改变

四、其他校验规则


一、实现添加用户功能

1、创建项目

2、修改pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.nari</groupId>
  <artifactId>12-springboot-validate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
     <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.RELEASE</version>
  </parent>
  
   <!-- 修改jdk版本 -->
  <properties>
  	<java.version>1.8</java.version>
  	<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
 	<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
  </properties>
  
  <dependencies>
	<!-- springBoot的启动器 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<!-- thymeleaf的启动器 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
	
    <!-- SpringBoot热部署插件 -->
	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
	</dependency>
  </dependencies>
  
</project>

3、编写添加用户功能

3.1、创建实体类

package com.nari.pojo;
public class Users {
	private String name;
	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 + "]";
	}
	
}

3.2、编写Controller

package com.nari.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.nari.pojo.Users;

/**
 * SpringBoot 表单数据校验:
 */
@Controller
public class UserController {

	@RequestMapping("addUser")
	public String showPage() {
		return "add";
	}
	
	//完成用户添加
	@RequestMapping("/save")
	public String saveUser(Users users) {
		System.out.println("users");
		return "ok";
	}
}

3.3、编写页面add.html,ok.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>添加用户</title>

</head>

<body>

    <form th:action="@{/save}" method="post">

        用户姓名:<input type="text" name="name"/><br/>

        用户密码:<input type="password" name="password" /><br/>

        用户年龄:<input type="text" name="age" /><br/>

        <input type="submit" value="OK"/>

    </form>

</body>

</html>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>操作成功</title>

</head>

<body>

    OK。。。。

</body>

</html>

二、SpringBoot对表单做数据校验

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

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

2、SpringBoot表单数据校验步骤

2.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";

    }

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.4、遇到异常

三、解决数据校验时的异常问题

解决异常的方法,在跳转页面的方法中注入一个对象,来解决问题。要求参数对象的变量名必须是对象的类名的全称首字母小写。

1、修改代码:

/**

     * 解决异常的方式。可以在跳转页面的方法中注入一个Uesrs对象。

     * 注意:由于springmvc会将该对象放入到Model中传递。key的名称会使用该对象的驼峰式的命名规则来作为key。

     * 参数的变量名需要与对象的名称相同。将首字母小写。

     *

     * @param users

     * @return

     */

    @RequestMapping("/addUser")

    public String showPage( Users users){

        return "add";

    }

/**

     * 完成用户添加

     *@Valid 开启对Users对象的数据校验

     *BindingResult:封装了校验的结果

     */

    @RequestMapping("/save")

    public String saveUser( @Valid Users users,BindingResult result){

        if(result.hasErrors()){

            return "add";

        }

        System.out.println(users);

        return "ok";

    }

<!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、如果参数的名称需要做改变

    /**

     *

     * 如果想为传递的对象更改名称,可以使用@ModelAttribute("aa")这表示当前传递的对象的key为aa

     * 那么我们在页面中获取该对象的key也需要修改为aa

     * @param users

     * @return

     */

    @RequestMapping("/addUser")

    public String showPage(@ModelAttribute("aa") Users users){

        return "add";

    }

/**

     * 完成用户添加

     *@Valid 开启对Users对象的数据校验

     *BindingResult:封装了校验的结果

     */

    @RequestMapping("/save")

    public String saveUser(@ModelAttribute("aa") @Valid Users users,BindingResult result){

        if(result.hasErrors()){

            return "add";

        }

        System.out.println(users);

        return "ok";

    }

<!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="${aa.name}"></font><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>

四、其他校验规则

@NotBlank: 判断字符串是否为null或者是空串(去掉首尾空格)。

@NotEmpty: 判断字符串是否null或者是空串。

@Length: 判断字符的长度(最大或者最小)

@Min: 判断数值最小值

@Max: 判断数值最大值

@Email: 判断邮箱是否合法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值