• Spring Boot DTO 验证示例


    在本教程中,我们将学习如何使用 Hibernate 验证器验证 Spring 启动 REST API DTO 请求。

    在Java中,Java Bean Validation框架已经成为处理Java项目中验证的事实标准。

    JSR 380 是用于 Bean 验证的 Java API 规范,它使用 @NotNull、@Min 和 @Max 等注释确保 Bean 的属性满足特定条件。

    Hibernate验证器是验证API的参考实现。

    我们创建并使用DTO(数据传输对象)在客户端和服务器之间转换数据。

    数据传输对象设计模式是一种常用的设计模式。它基本上用于一次性将具有多个属性的数据从客户端传递到服务器,以避免多次调用远程服务器。

    我们不会将 Java Bean 验证注释添加到 JPA 实体,而是将 Java Bean 验证注释添加到 DTO,因为我们将在 REST API 的请求和响应中使用 DTO。

    重要的 Java Bean 验证

    • @NotNull验证批注的属性值是否不为 null。
    • @Size验证批注属性值的大小是否介于属性 min 和 max 之间;可以应用于字符串、集合、映射和数组属性。
    • @Min验证批注属性的值不小于 value 属性。
    • @Max验证批注属性的值不大于 value 属性。
    • @Email验证批注属性是否为有效的电子邮件地址。
    • @NotEmpty验证属性是否为空或空;可以应用于字符串、集合、映射或数组值。
    • @NotBlank只能应用于文本值,并验证属性是否为 null 或空格。
    在此处查看完整列表Source Code Examples

    Spring 引导中的验证

    Spring boot 提供了与 Hibernate 验证器的良好集成支持。

    我们将使用 Hibernate Validator,它是 Bean 验证 API 的参考实现之一。

    从 Boot 2.3 开始,我们需要显式添加spring-boot-starter-validation依赖项:

    1. org.springframework.boot
    2. spring-boot-starter-validation

    弹簧引导 DTO 验证示例

    让我们创建一个分步示例来演示如何使用 Hibernate 验证器验证 Spring 启动 REST API DTO 请求。

    1. 在 STS 中创建 Spring 引导应用程序

    使用以下指南在 Eclipse STS IDE 中创建 Spring 引导项目:
    - 将项目名称作为弹簧启动验证
    - 将以下依赖项添加到此项目:
    • 春网
    • 验证
    • 春季数据 JPA
    • H2 数据库

    2. Maven 依赖项

    创建 Spring 引导项目后,使用以下pom.xml 文件验证您的pom.xml
    1. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    2. 4.0.0
    3. org.springframework.boot
    4. spring-boot-starter-parent
    5. 2.4.3
    6. net.javaguides
    7. springboot-validation
    8. 0.0.1-SNAPSHOT
    9. springboot-validation
    10. Demo project for Spring Boot and Hibernate Validator
    11. 1.8
    12. org.springframework.boot
    13. spring-boot-starter-data-jpa
    14. org.springframework.boot
    15. spring-boot-starter-validation
    16. org.springframework.boot
    17. spring-boot-starter-web
    18. com.h2database
    19. h2
    20. runtime
    21. org.springframework.boot
    22. spring-boot-starter-test
    23. test
    24. org.springframework.boot
    25. spring-boot-maven-plugin

    3. 创建用户类

    让我们创建一个新的模型包。在此模型包中,创建一个用户JPA 类并向其中添加以下内容:
    1. package net.javaguides.springboot.model;
    2. import javax.persistence.Column;
    3. import javax.persistence.Entity;
    4. import javax.persistence.GeneratedValue;
    5. import javax.persistence.GenerationType;
    6. import javax.persistence.Id;
    7. import javax.persistence.Table;
    8. @Table(name = "users")
    9. @Entity
    10. public class User {
    11. @Id
    12. @GeneratedValue(strategy = GenerationType.IDENTITY)
    13. private long id;
    14. @Column(name = "name", nullable = false)
    15. private String name;
    16. private String email;
    17. private String password;
    18. public User() {
    19. }
    20. public User(String name, String email, String password) {
    21. super();
    22. this.name = name;
    23. this.email = email;
    24. this.password = password;
    25. }
    26. public long getId() {
    27. return id;
    28. }
    29. public void setId(long id) {
    30. this.id = id;
    31. }
    32. public String getName() {
    33. return name;
    34. }
    35. public void setName(String name) {
    36. this.name = name;
    37. }
    38. public String getEmail() {
    39. return email;
    40. }
    41. public void setEmail(String email) {
    42. this.email = email;
    43. }
    44. public String getPassword() {
    45. return password;
    46. }
    47. public void setPassword(String password) {
    48. this.password = password;
    49. }
    50. }

    4. 创建用户Dto 类

    让我们创建一个dto包。在dto包中,创建UserDto类并向其中添加以下内容:
    1. package net.javaguides.springboot.dto;
    2. import javax.validation.constraints.Email;
    3. import javax.validation.constraints.NotEmpty;
    4. import javax.validation.constraints.Size;
    5. public class UserDto {
    6. private long id;
    7. // user name should not be null or empty
    8. // user name should have at least 2 characters
    9. @NotEmpty
    10. @Size(min = 2, message = "user name should have at least 2 characters")
    11. private String name;
    12. // email should be a valid email format
    13. // email should not be null or empty
    14. @NotEmpty
    15. @Email
    16. private String email;
    17. // password should not be null or empty
    18. // password should have at least 8 characters
    19. @NotEmpty
    20. @Size(min = 8, message = "password should have at least 8 characters")
    21. private String password;
    22. public UserDto() {
    23. }
    24. public UserDto(String name, String email, String password) {
    25. super();
    26. this.name = name;
    27. this.email = email;
    28. this.password = password;
    29. }
    30. public long getId() {
    31. return id;
    32. }
    33. public void setId(long id) {
    34. this.id = id;
    35. }
    36. public String getName() {
    37. return name;
    38. }
    39. public void setName(String name) {
    40. this.name = name;
    41. }
    42. public String getEmail() {
    43. return email;
    44. }
    45. public void setEmail(String email) {
    46. this.email = email;
    47. }
    48. public String getPassword() {
    49. return password;
    50. }
    51. public void setPassword(String password) {
    52. this.password = password;
    53. }
    54. }

    请注意,我们在下面添加了 Java Bean 验证注释到UserDto类:

    • @NotEmpty验证属性是否为空或空;可以应用于字符串、集合、映射或数组值。
    • @Size验证批注属性值的大小是否介于属性 min 和 max 之间;可以应用于字符串、集合、映射和数组属性。
    • @Email验证批注属性是否为有效的电子邮件地址。

    5. 配置数据库

    Spring boot 会自动为 H2 内存数据库配置数据库详细信息,因此我们无需在application.properties文件中显式添加数据库配置。

    6. 创建用户存储库

    让我们创建一个存储库包。在此包中,创建一个与数据库通信的UserRepository类。添加以下内容:
    1. package net.javaguides.springboot.repository;
    2. import org.springframework.data.jpa.repository.JpaRepository;
    3. import net.javaguides.springboot.model.User;
    4. public interface UserRepository extends JpaRepository{
    5. }

    7. 创建用户服务类

    让我们创建一个服务包。在此包中,创建一个UserService类并向其中添加以下代码:
    1. package net.javaguides.springboot.service;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.stereotype.Service;
    4. import net.javaguides.springboot.model.User;
    5. import net.javaguides.springboot.repository.UserRepository;
    6. @Service
    7. public class UserService {
    8. @Autowired
    9. private UserRepository userRepository;
    10. public User createUser(User user) {
    11. return userRepository.save(user);
    12. }
    13. }

    8. 创建用户控制器类

    让我们创建一个控制器包。在此包中,创建一个UserController类并向其添加以下内容:
    1. package net.javaguides.springboot.controller;
    2. import javax.validation.Valid;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.http.HttpStatus;
    5. import org.springframework.http.ResponseEntity;
    6. import org.springframework.web.bind.annotation.PostMapping;
    7. import org.springframework.web.bind.annotation.RequestBody;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RestController;
    10. import net.javaguides.springboot.model.User;
    11. import net.javaguides.springboot.dto.UserDto;
    12. import net.javaguides.springboot.service.UserService;
    13. @RestController
    14. @RequestMapping("/api/")
    15. public class UserController {
    16. @Autowired
    17. private UserService userService;
    18. @PostMapping("users")
    19. public ResponseEntity createUser(@Valid @RequestBody UserDto userDto){
    20. // convert UserDto to User entity
    21. User user = new User();
    22. user.setName(userDto.getName());
    23. user.setEmail(userDto.getEmail());
    24. user.setPassword(userDto.getPassword());
    25. User savedUser = userService.createUser(user);
    26. // convert User entity to UserDto class
    27. UserDto userResponse = new UserDto();
    28. userResponse.setId(savedUser.getId());
    29. userResponse.setName(savedUser.getName());
    30. userResponse.setEmail(savedUser.getEmail());
    31. // don't provide password to client
    32. // userResponse.setPassword(savedUser.getPassword());
    33. return new ResponseEntity(userResponse, HttpStatus.CREATED);
    34. }
    35. }
    请注意,我们通过在createUser() 方法中添加@Valid注释来启用 Spring Rest 控制器上的验证@RequestBody。

    9. 创建验证处理程序

    让我们创建一个验证处理程序来自定义验证响应。
    要自定义响应验证,我们需要扩展ResponseEntityExceptionHandler类并覆盖handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request)方法。
    让我们创建ValidationHandler类并向其添加以下内容:
    1. package net.javaguides.springboot.controller;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. import org.springframework.http.HttpHeaders;
    5. import org.springframework.http.HttpStatus;
    6. import org.springframework.http.ResponseEntity;
    7. import org.springframework.validation.FieldError;
    8. import org.springframework.web.bind.MethodArgumentNotValidException;
    9. import org.springframework.web.bind.annotation.ControllerAdvice;
    10. import org.springframework.web.context.request.WebRequest;
    11. import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
    12. @ControllerAdvice
    13. public class ValidationHandler extends ResponseEntityExceptionHandler{
    14. @Override
    15. protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
    16. HttpHeaders headers, HttpStatus status, WebRequest request) {
    17. Map errors = new HashMap<>();
    18. ex.getBindingResult().getAllErrors().forEach((error) ->{
    19. String fieldName = ((FieldError) error).getField();
    20. String message = error.getDefaultMessage();
    21. errors.put(fieldName, message);
    22. });
    23. return new ResponseEntity(errors, HttpStatus.BAD_REQUEST);
    24. }
    25. }
    26. 10.运行弹簧启动应用程序

      使用主类运行 Spring 引导应用程序:
      1. package net.javaguides.springboot;
      2. import org.springframework.boot.SpringApplication;
      3. import org.springframework.boot.autoconfigure.SpringBootApplication;
      4. @SpringBootApplication
      5. public class SpringbootValidationApplication {
      6. public static void main(String[] args) {
      7. SpringApplication.run(SpringbootValidationApplication.class, args);
      8. }
      9. }

      11. 使用邮递员客户端进行测试

      下面的屏幕截图显示了使用Hibernate验证器对Spring boot REST API的验证:

       

      11. 结论

      在本教程中,我们学习了如何使用Hibernate验证器在Spring boot REST API中验证DTO对象。

      本教程的源代码可在我的 GitHub 存储库中找到,网址为GitHub - RameshMF/springboot-validation: Validation in Spring Boot REST API with Hibernate Validator (Java Bean Validation Annotations)

      从 Boot 2.3 开始,我们需要显式添加spring-boot-starter-validation依赖项:

       
          org.springframework.boot 
          spring-boot-starter-validation 
      

       

    27. 相关阅读:
      浅谈ChatGPT
      二叉树最大宽度 : 简单 DFS 运用题
      Spring 中BeanFactory和FactoryBean有什么不同之处呢?
      IDEA 配置 Maven(解决依赖下载缓慢)
      必看!TMS320C6678+Kintex-7开发板——FPGA案例开发资料(上)
      redis未授权漏洞
      Mysql.索引详解
      Vim 使用操作
      [思维]Party Codeforces1711B
      【Flink伪分布式环境搭建及应用,Standlong(开发测试)】
    28. 原文地址:https://blog.csdn.net/allway2/article/details/127786840