博客
关于我
springboot服务端数据校验
阅读量:716 次
发布时间:2019-03-21

本文共 5611 字,大约阅读时间需要 18 分钟。

Spring Boot 数据校验技术详解

Spring Boot 提供了强大的数据校验功能,结合 Hibernate Validator框架,开发者可以轻松实现对象属性的校验规则。通过合理配置和注解,能够有效防止数据异常情况,提高系统可靠性。本文将详细介绍 Spring Boot 数据校验的技术特点、实体对象校验的实现方式以及常见的测试案例。

校验依赖配置

在项目的 pom.xml 文件中,需要引入 Hibernate Validator 的相关依赖。具体配置如下:

org.hibernate.validator
hibernate-validator
6.0.0.Final

这一步是为后续使用 @NotNull@NotBlank 等校验注解准备依赖,确保系统能够正常识别并使用这些校验功能。

实体对象校验

在业务对象(POPO)中,我们可以通过注解快速实现基础数据校验。常用的校验注解包括:

  • @NotNull:用于基本数据类型(如 Integer、Double)进行非空校验。
  • @NotBlank:用于 String 类型的字段,专门用于检测是否为空。
  • @NotEmpty:用于集合类型的字段,检测是否为空集合。

以下是一个典型的示例:

private Integer id;@NotNull(message = "{name.notnull}")private String name;@NotNull(message = "{price.notnull}")private Double price;@NotNull(message = "{production.notnull}")private String production;

注:{name.notnull} 这种格式是用于自定义提示信息的,在 ValidationMessages.properties 配置文件中,应将对应的键值定义为所需提示内容。

数据校验流程

在.controller 中,提供一个示例:

@RequestMapping("/addFlower")public String addFlower(@Validated Flower flower, BindingResult result, HttpServletRequest request) {    if (result.hasErrors()) {        for (ObjectError err : result.getAllErrors()) {            FieldError fieldError = (FieldError) err;            System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());        }    }    try {        flowerService.addFlower(flower);        return "redirect:/flower/show";    } catch (Exception e) {        return "error";    }}
  • @Validated 注解用于标注需要校验的业务对象。
  • BindingResult 对象提供了校验结果,用于反馈校验错误。
  • result.hasErrors() 用于判断是否存在校验错误。
  • result.getAllErrors() 获取所有校验错误,推荐使用 ObjectErrorFieldError 来处理错误信息。

错误信息处理

在前台页面中,使用 Thymeleaf 模板引擎可以显示校验错误提示。例如,定义一个 error.html 页面:

    ERROR    

ERROR

自定义提示信息

为了实现个性化的提示信息,可以使用 ValidationMessages.properties 配置文件。将其放在 src/main/resources 目录下,内容格式为:

name.notnull=花卉名称不能为空price.notnull=花卉价格不能为空production.notnull=花卉产地不能为空

在业务对象中使用自定义提示:

private Integer id;@NotBlank(message = "{name.notnull}")private String name;@NotNull(message = "{price.notnull}")private Double price;@NotBlank(message = "{production.notnull}")private String production;

乘码问题解决

清晰字符编码设置可以防止乱码,建议在数据库连接 URL 中添加 useUnicode=truecharacterEncoding=utf-8 参数。例如:

spring.datasource.url= jdbc:mysql://localhost:3306/login?useUnicode=true&characterEncoding=utf-8&useSSl=false

通过这些配置,Unicode 字符会正确转换为 UTF-8 编码,避免乱码问题。

其他校验规则

除了基础非空校验,Spring Boot 还支持多种校验注解组合使用。例如:

  • @Size(min=1, max=100):用于字符串长度校验,minmax 为闭区间。
  • @PastOrCurrent():用于日期范围校验。

以下是一个实际使用案例:

public class Flower {    private Integer id;    @NotBlank(message = "{name.notnull}")    private String name;    @NotNull(message = "{price.notnull}")    @Size(min=1, max=100, message = "价格范围必须在 1 到 100 之间")    private Double price;    @NotBlank(message = "{production.notnull}")    private String production;}

绕过因素服务

在.controller 中,可以使用 @ModelAttribute 注注特定键名获取数据,并将校验结果注入到前台页面。例如:

@Controller@RequestMapping("flower")public class FlowerController {    @Autowired    FlowerService flowerService;    @RequestMapping("/addFlower")    public String addFlower(@ModelAttribute("a") @Validated Flower flower, BindingResult result, HttpServletRequest request) {        try {            if (!result.hasErrors()) {                flowerService.addFlower(flower);                return "main";            } catch (Exception e) {                System.out.println(e.toString());                return "error";            }        }    }    @RequestMapping("/show")    public String selAllFlower(HttpServletRequest request, @ModelAttribute("a") Flower flower) {        List
list = flowerService.selAllFlower(); request.getSession().setAttribute("flowers", list); return "main"; }}

这种方式可以确保前台页面在不存在校验错误时,仍能顺利显示数据,并避免因校验失败导致的 BindingResult 传递错误。

配置校验信息到 mateModelAttribute

为了方便前台页面使用,其 Berger propia 可以直接注入。例如:

@Controller@RequestMapping("flower")public class FlowerController {    @Autowired    FlowerService flowerService;    @RequestMapping("/addFlower")    public String addFlower(@Validated Flower flower, BindingResult result) {        try {            if (!result.hasErrors()) {                flowerService.addFlower(flower);                return "main";            } catch (Exception e) {                return "error";            }        }    }}

前台展示错误信息

在前台页面中,使用 Thymeleaf 查找错误信息。例如:

花卉名称不能为空

全局异常处理

通过 GlobalException 配置类,确保不同类型的异常都能正确处理,返回友好的错误页面。例如:

@Configurationpublic class GlobalException implements HandlerExceptionResolver {    @Override    public ModelAndView resolveException(        HttpServletRequest request,        HttpServletResponse response,        Object handler,        Exception e) {        ModelAndView mv = new ModelAndView();        if (e instanceof ConstraintViolationException) {            mv.setViewName("main");        }        mv.addObject("err", e.toString().split(":")[2]);        return mv;    }}

项目结构

项目的基本目录结构如下:

/src├── main│   ├── java│   │   └── cn/wit.springbootmybatis│   │       ├── controller│   │       ├── exception│   │       ├── mapper│   │       ├── pojo│   │       ├── service│   │       └── validator│   ├── resources│   │   ├── static│   │   └── templates│   └── test│       └── java│           └── cn/wit.springbootmybatis

后台代码示例

一个完整的 FlowerService 和其实现类:

public interface FlowerService {    void addFlower(Flower flower);    void delFlower(int id);    List
selAllFlower(); void updPriceFlower(Flower flower); Flower preUpdateFlower(int id); List
selFlowerByName(String name);}

pom.xml defaultProject

com.alibaba
druid
1.1.12

以上是完成的技术文档优化版,涵盖了 Spring Boot 数据校验的核心内容,既保持了技术贴士,又符合用户要求的表述方式。

转载地址:http://nvqez.baihongyu.com/

你可能感兴趣的文章
n 叉树后序遍历转换为链表问题的深入探讨
查看>>
N!
查看>>
N-Gram的基本原理
查看>>
n1 c语言程序,全国青少年软件编程等级考试C语言经典程序题10道七
查看>>
Nacos Client常用配置
查看>>
nacos config
查看>>
Nacos Config--服务配置
查看>>
Nacos Derby 远程命令执行漏洞(QVD-2024-26473)
查看>>
Nacos 与 Eureka、Zookeeper 和 Consul 等其他注册中心的区别
查看>>
Nacos 单机集群搭建及常用生产环境配置 | Spring Cloud 3
查看>>
Nacos 启动报错[db-load-error]load jdbc.properties error
查看>>
Nacos 报Statement cancelled due to timeout or client request
查看>>
Nacos 注册服务源码分析
查看>>
Nacos 融合 Spring Cloud,成为注册配置中心
查看>>
Nacos-注册中心
查看>>
Nacos-配置中心
查看>>
Nacos2.X 源码分析:为订阅方推送、服务健康检查、集群数据同步、grpc客户端服务端初始化
查看>>
Nacos2.X 配置中心源码分析:客户端如何拉取配置、服务端配置发布客户端监听机制
查看>>
Nacos2.X源码分析:服务注册、服务发现流程
查看>>
NacosClient客户端搭建,微服务注册进nacos
查看>>