本文共 5611 字,大约阅读时间需要 18 分钟。
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() 获取所有校验错误,推荐使用 ObjectError 和 FieldError 来处理错误信息。在前台页面中,使用 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=true 和 characterEncoding=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):用于字符串长度校验,min 和 max 为闭区间。@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 传递错误。
为了方便前台页面使用,其 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);}           com.alibaba druid 1.1.12 
以上是完成的技术文档优化版,涵盖了 Spring Boot 数据校验的核心内容,既保持了技术贴士,又符合用户要求的表述方式。
转载地址:http://nvqez.baihongyu.com/