在Spring Boot中实现表单字段校验的教程

夏伟大大_2306

夏伟大大_2306

2025-12-12

307人浏览

原创

在Spring Boot中实现表单字段校验的教程

本教程详细介绍了如何在spring boot应用中实现表单字段校验,涵盖了服务器端和客户端两种方法。服务器端通过引入`spring-boot-starter-validation`依赖,在模型(pojo)中使用`@notblank`、`@min`等jsr 303/380注解,并在控制器方法中结合`@valid`和`@modelattribute`进行校验。客户端则利用html5的`required`属性和合适的`input`类型提供即时反馈。结合使用这两种方法能有效提升应用的数据完整性和用户体验。

在构建Web应用时,表单数据校验是确保数据完整性和提升用户体验的关键环节。Spring Boot提供了强大的校验机制,结合HTML5的客户端校验,可以构建健壮的表单处理流程。本教程将详细阐述如何在Spring Boot项目中为表单字段添加必填校验。

一、理解校验的重要性

在用户提交表单数据时,如果某些关键字段缺失或格式不正确,可能导致后端业务逻辑错误,甚至引发应用异常(如本例中未输入价格导致的Whitelabel Error Page)。因此,无论是在客户端还是服务器端,都必须对用户输入进行严格的校验。

二、服务器端校验:使用Spring Validation

Spring Boot通过集成JSR 303/380 (Bean Validation) 规范,提供了强大的服务器端校验能力。

1. 引入校验依赖

首先,需要在pom.xml文件中添加spring-boot-starter-validation依赖。这个依赖包含了Hibernate Validator,它是JSR 303/380规范的一个实现。

<dependency><groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-validation</artifactid></dependency>

2. 在模型(POJO)中定义校验规则

在代表表单数据的POJO类(例如Product类)的字段上,使用JSR 303/380提供的注解来定义校验规则。

  • @NotBlank: 适用于字符串,表示字段不能为空且不能只包含空白字符。
  • @NotNull: 适用于任何类型,表示字段不能为null。
  • @NotEmpty: 适用于字符串、集合、数组,表示字段不能为null且长度或大小不能为0。
  • @Min(value): 适用于数值类型,表示字段值必须大于或等于指定值。
  • @Max(value): 适用于数值类型,表示字段值必须小于或等于指定值。
  • @Size(min=x, max=y): 适用于字符串、集合、数组,表示字段的长度或大小必须在指定范围内。
  • @Email: 适用于字符串,表示字段必须是有效的电子邮件格式。

以下是为Product类添加校验注解的示例:

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "products")
public class Product {

    @Id
    private String id;

    @NotBlank(message = "产品名称不能为空") // 产品名称不能为空
    private String prodName;

    @NotBlank(message = "产品描述不能为空") // 产品描述不能为空
    private String prodDesc;

    @Min(value = 0, message = "产品价格不能为负数") // 产品价格不能小于0
    private Double prodPrice;

    // prodImage可以为空,如果需要必填,可以添加@NotBlank
    private String prodImage;

    public Product() {
    }

    public Product(String prodName, String prodDesc, Double prodPrice, String prodImage) {
        this.prodName = prodName;
        this.prodDesc = prodDesc;
        this.prodPrice = prodPrice;
        this.prodImage = prodImage;
    }

    // Getters and Setters
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getProdName() { return prodName; }
    public void setProdName(String prodName) { this.prodName = prodName; }
    public String getProdDesc() { return prodDesc; }
    public void setProdDesc(String prodDesc) { this.prodDesc = prodDesc; }
    public Double getProdPrice() { return prodPrice; }
    public void setProdPrice(Double prodPrice) { this.prodPrice = prodPrice; }
    public String getProdImage() { return prodImage; }
    public void setProdImage(String prodImage) { this.prodImage = prodImage; }
}

注意:@Min(0.01d)可以确保价格大于0,如果允许价格为0,则使用@Min(0d)。

3. 在控制器中触发校验

在控制器方法中,将表单数据绑定到带有校验注解的POJO对象上,并通过@Valid注解触发校验。同时,为了捕获校验结果,通常会紧跟一个BindingResult参数。

import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Controller
public class ProductController {

    @Autowired
    ProductRepository productRepository;

    // ... 其他方法 ...

    @RequestMapping(value = "/save", method = RequestMethod.POST) // 推荐使用POST方法处理表单提交
    public String save(@Valid @ModelAttribute Product product, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            // 如果有校验错误,返回到创建页面并显示错误信息
            model.addAttribute("product", product); // 将带有错误的product对象传回表单
            model.addAttribute("errors", bindingResult.getAllErrors()); // 传递所有错误信息
            return "create"; // 返回到创建产品页面
        }

        productRepository.save(product);
        return "redirect:/show/" + product.getId();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST) // 推荐使用POST方法处理表单提交
    public String update(@Valid @ModelAttribute Product product, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            // 如果有校验错误,返回到编辑页面并显示错误信息
            model.addAttribute("product", product);
            model.addAttribute("errors", bindingResult.getAllErrors());
            return "edit"; // 返回到编辑产品页面
        }

        // 确保ID不丢失
        Optional<product> existingProduct = productRepository.findById(product.getId());
        if (existingProduct.isPresent()) {
            Product p = existingProduct.get();
            p.setProdName(product.getProdName());
            p.setProdDesc(product.getProdDesc());
            p.setProdPrice(product.getProdPrice());
            p.setProdImage(product.getProdImage());
            productRepository.save(p);
        } else {
            // 处理产品不存在的情况,例如重定向到错误页或产品列表
            return "redirect:/product";
        }

        return "redirect:/show/" + product.getId();
    }

    @RequestMapping("/create")
    public String create(Model model) {
        model.addAttribute("product", new Product()); // 为表单提供一个空的Product对象
        return "create";
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable String id, Model model) {
        model.addAttribute("product", productRepository.findById(id).orElse(new Product())); // 确保不会返回null
        return "edit";
    }

    // ... 其他方法 ...
}</product>

重要提示:

  • 将@RequestParam替换为@ModelAttribute Product product,这样Spring会自动将表单参数绑定到Product对象的属性上。
  • @Valid注解告诉Spring对Product对象执行校验。
  • BindingResult参数必须紧跟在@Valid参数之后,它包含了校验结果,通过hasErrors()方法可以判断是否存在错误。
  • 在create和edit方法中,确保为模板提供一个Product对象,以便Thymeleaf能够正确绑定表单数据和显示错误。

4. 在Thymeleaf模板中显示校验错误

当BindingResult检测到错误时,可以将错误信息传递回前端页面进行显示。

在create.html和edit.html中,可以这样显示错误信息:

CDP浏览器大师
CDP浏览器大师

CDP浏览器大师:通过Chrome DevTools Protocol驱动已登录浏览器实现自动化任务,解决反爬封号、选择器失效、SPA路由难导航、固定sleep不准四大痛点。核心能力包括UA伪装、WebGL/Canvas指纹混淆、智能等待、动态选择器以及可视化调试。

下载
<!-- 在表单顶部或其他位置显示所有全局错误 -->
<div th:if="${#fields.hasErrors('global')}" class="alert alert-danger">
    <p th:each="err : ${#fields.errors('global')}" th:text="${err}"></p>
</div>

<!-- 为每个字段显示具体的错误信息 -->
<div class="form-group" th:classappend="${#fields.hasErrors('prodName')} ? 'has-error'">
    <label for="prodName">Product Name:</label>
    <input type="text" class="form-control" name="prodName" th:field="*{prodName}"><span th:if="${#fields.hasErrors('prodName')}" th:errors="*{prodName}" class="help-block text-danger"></span>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('prodDesc')} ? 'has-error'">
    <label for="prodDesc">Product Description</label>
    <textarea class="form-control" name="prodDesc" cols="60" rows="3" th:field="*{prodDesc}"></textarea><span th:if="${#fields.hasErrors('prodDesc')}" th:errors="*{prodDesc}" class="help-block text-danger"></span>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('prodPrice')} ? 'has-error'">
    <label for="prodPrice">Product Price</label>
    <input type="number" class="form-control" name="prodPrice" th:field="*{prodPrice}"><span th:if="${#fields.hasErrors('prodPrice')}" th:errors="*{prodPrice}" class="help-block text-danger"></span>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('prodImage')} ? 'has-error'">
    <label for="prodImage">Product Image URL:</label>
    <input type="url" class="form-control" name="prodImage" th:field="*{prodImage}"><span th:if="${#fields.hasErrors('prodImage')}" th:errors="*{prodImage}" class="help-block text-danger"></span>
</div>

注意:

  • th:field="*{prodName}" 是Thymeleaf的表单绑定语法,它会自动设置name、id和value属性。
  • th:classappend="${#fields.hasErrors('prodName')} ? 'has-error'" 会在字段有错误时添加has-error类,通常用于样式高亮。
  • th:errors="*{prodName}" 会显示该字段的错误消息。
  • th:if="${#fields.hasErrors('prodName')}" 用于条件性地显示错误消息。
  • 为了使th:field正常工作,form标签需要使用th:object="${product}"来指定绑定的对象。

修改create.html和edit.html的form标签如下:

<!-- create.html -->

三、客户端校验:使用HTML5 required属性

客户端校验可以在用户提交表单之前提供即时反馈,提升用户体验并减轻服务器压力。HTML5提供了required属性以及各种input类型(如type="number"、type="url")来实现基本的客户端校验。

1. 使用 required 属性

在需要必填的input、textarea或select元素上添加required属性。

<!-- create.html 和 edit.html -->
<div class="form-group">
    <label for="prodName">Product Name:</label>
    <input type="text" class="form-control" name="prodName" th:field="*{prodName}" required>
</div>
<div class="form-group">
    <label for="prodDesc">Product Description</label>
    <textarea class="form-control" name="prodDesc" cols="60" rows="3" th:field="*{prodDesc}" required></textarea>
</div>
<div class="form-group">
    <label for="prodPrice">Product Price</label>
    <input type="number" class="form-control" name="prodPrice" th:field="*{prodPrice}" required>
</div>
<div class="form-group">
    <label for="prodImage">Product Image URL:</label>
    <input type="url" class="form-control" name="prodImage" th:field="*{prodImage}">
</div>

注意:

  • required属性是布尔属性,只需存在即生效。
  • type="number"会限制用户只能输入数字,并且浏览器会提供步进器(如果支持)。
  • type="url"会要求用户输入符合URL格式的字符串。
  • label的for属性应与input的id属性对应,以提高可访问性。为了避免冲突,建议将label的for属性值修改为与name属性值一致(或使用th:field自动生成的id)。

四、结合使用客户端与服务器端校验

最佳实践是同时使用客户端和服务器端校验:

  • 客户端校验:提供即时、友好的用户反馈,减少不必要的服务器请求。
  • 服务器端校验:作为最终防线,确保数据的完整性和安全性,因为客户端校验容易被绕过。

当客户端校验通过后,数据提交到服务器,服务器端会再次进行校验。如果服务器端校验失败,则将错误信息返回给客户端,由客户端页面显示。

五、总结

通过本教程,我们学习了如何在Spring Boot应用中实现表单字段的必填校验。核心步骤包括:

  1. 添加spring-boot-starter-validation依赖。
  2. 在POJO模型中使用JSR 303/380校验注解(如@NotBlank, @Min)。
  3. 在控制器方法中使用@Valid和@ModelAttribute触发校验,并利用BindingResult处理校验结果。
  4. 在Thymeleaf模板中显示校验错误信息,并使用th:field进行表单绑定。
  5. 在HTML表单中使用required属性和合适的input类型进行客户端校验,提升用户体验。

结合使用这两种校验方法,能够有效地保障应用程序的数据质量,提高系统的健壮性和用户满意度。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

2025.08.06

2851

22

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

2026.01.26

517

25

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

2023.09.05

691

5

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

2023.10.12

1455

7

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

2025.08.19

5546

10

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

2025.12.22

436

5

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

2025.12.24

680

18

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

2026.02.11

405

24

Kotlin协程编程与Spring Boot集成实践
Kotlin协程编程与Spring Boot集成实践

本专题围绕 Kotlin 协程机制展开,深入讲解挂起函数、协程作用域、结构化并发与异常处理机制,并结合 Spring Boot 展示协程在后端开发中的实际应用。内容涵盖异步接口设计、数据库调用优化、线程资源管理以及性能调优策略,帮助开发者构建更加简洁高效的 Kotlin 后端服务架构。

2026.02.12

391

18

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
GDB 17.2 官方文档集合
GDB 17.2 官方文档集合

共0课时 | 0人学习

Bootstrap 入门安装配置
Bootstrap 入门安装配置

共0课时 | 0人学习

38+ PhpStorm 提示和技巧
38+ PhpStorm 提示和技巧

共1课时 | 237人学习