Validation in Spring Boot – Spring Boot中的验证

最后修改: 2019年 2月 7日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

When it comes to validating user input, Spring Boot provides strong support for this common, yet critical, task straight out of the box.

在验证用户输入时,Spring Boot直接为这项常见但关键的任务提供了强大的支持。

Although Spring Boot supports seamless integration with custom validators, the de-facto standard for performing validation is Hibernate Validator, the Bean Validation framework’s reference implementation.

虽然Spring Boot支持与自定义验证器的无缝集成,但执行验证的事实标准是Hibernate验证器Bean验证框架的参考实现。

In this tutorial, we’ll look at how to validate domain objects in Spring Boot.

在本教程中,我们将研究如何在Spring Boot中验证域对象

2. The Maven Dependencies

2.Maven的依赖性

In this case, we’ll learn how to validate domain objects in Spring Boot by building a basic REST controller.

在这个案例中,我们将学习如何通过建立一个基本的REST控制器来验证Spring Boot中的域对象

The controller will first take a domain object, then it will validate it with Hibernate Validator, and finally it will persist it into an in-memory H2 database.

控制器将首先接受一个域对象,然后用Hibernate验证器进行验证,最后将其持久化到内存中的H2数据库。

The project’s dependencies are fairly standard:

这个项目的依赖性是相当标准的。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> 
<dependency> 
    <groupId>com.h2database</groupId> 
    <artifactId>h2</artifactId>
    <version>1.4.197</version> 
    <scope>runtime</scope>
</dependency>

As shown above, we included spring-boot-starter-web in our pom.xml file because we’ll need it for creating the REST controller. Additionally, let’s make sure to check the latest versions of spring-boot-starter-jpa and the H2 database on Maven Central.

如上所示,我们在spring-boot-starter-web中包含了pom.xml文件,因为我们需要它来创建REST控制器。此外,让我们确保在Maven中心检查spring-boot-starter-jpaH2数据库的最新版本。

Starting with Boot 2.3, we also need to explicitly add the spring-boot-starter-validation dependency:

从Boot 2.3开始,我们还需要明确添加spring-boot-starter-validation依赖。

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

3. A Simple Domain Class

3.一个简单的域类

With our project’s dependencies already in place, next we need to define an example JPA entity class, whose role will solely be modelling users.

由于我们项目的依赖性已经到位,接下来我们需要定义一个JPA实体类的例子,它的作用将仅仅是为用户建模。

Let’s have a look at this class:

让我们来看看这个班级。

@Entity
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @NotBlank(message = "Name is mandatory")
    private String name;
    
    @NotBlank(message = "Email is mandatory")
    private String email;
    
    // standard constructors / setters / getters / toString
        
}

The implementation of our User entity class is pretty anemic indeed, but it shows in a nutshell how to use Bean Validation’s constraints to constrain the name and email fields.

我们的User实体类的实现确实相当贫乏,但它简要地展示了如何使用Bean Validation的约束来约束nameemail字段。

For simplicity’s sake, we constrained the target fields using only the @NotBlank constraint. Also, we specified the error messages with the message attribute.

为了简单起见,我们只用@NotBlank约束了目标字段。另外,我们用message属性指定了错误信息。

Therefore, when Spring Boot validates the class instance, the constrained fields must be not null and their trimmed length must be greater than zero.

因此,当Spring Boot验证类实例时,受限字段必须不是空的,其修剪后的长度必须大于零

Additionally, Bean Validation provides many other handy constraints besides @NotBlank. This allows us to apply and combine different validation rules to the constrained classes. For further information, please read the official bean validation docs.

此外,Bean Validation除了@NotBlank,还提供了许多其他方便的约束。这使得我们可以将不同的验证规则应用和组合到受约束的类中。欲了解更多信息,请阅读官方的Bean验证文档

Since we’ll use Spring Data JPA for saving users to the in-memory H2 database, we also need to define a simple repository interface for having basic CRUD functionality on User objects:

由于我们将使用Spring Data JPA来将用户保存到内存中的H2数据库,我们还需要定义一个简单的存储库接口,以便在User对象上拥有基本的CRUD功能。

@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

4. Implementing a REST Controller

4.实现一个REST控制器

Of course, we need to implement a layer that allows us to get the values assigned to our User object’s constrained fields.

当然,我们需要实现一个层,使我们能够获得分配给我们的User对象的受限字段的值。

Therefore, we can validate them and perform a few further tasks, depending on the validation results.

因此,我们可以根据验证结果,对它们进行验证,并执行一些进一步的任务。

Spring Boot makes this seemingly complex process really simple through the implementation of a REST controller.

Spring Boot通过实施REST控制器使这个看似复杂的过程变得非常简单

Let’s look at the REST controller implementation:

让我们来看看REST控制器的实现。

@RestController
public class UserController {

    @PostMapping("/users")
    ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        // persisting the user
        return ResponseEntity.ok("User is valid");
    }
    
    // standard constructors / other methods
    
}

In a Spring REST context, the implementation of the addUser() method is fairly standard.

Spring REST上下文中,addUser()方法的实现相当标准。

Of course, the most relevant part is the use of the @Valid annotation.

当然,最相关的部分是使用@Valid注解。

When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument.

当Spring Boot发现一个用@Valid注释的参数时,它会自动引导默认的JSR 380实现–Hibernate Validator–并验证该参数。

When the target argument fails to pass the validation, Spring Boot throws a MethodArgumentNotValidException exception.

当目标参数未能通过验证时,Spring Boot会抛出一个MethodArgumentNotValidException异常。

5. The @ExceptionHandler Annotation

5.@ExceptionHandler 注释

While it’s really handy to have Spring Boot validating the User object passed on to the addUser() method automatically, the missing facet of this process is how we process the validation results.

虽然让Spring Boot自动验证传递给User()方法的User对象真的很方便,但这个过程中缺少的是我们如何处理验证结果。

The @ExceptionHandler annotation allows us to handle specified types of exceptions through one single method.

@ExceptionHandler注解允许我们通过一个单一的方法处理指定类型的异常。

Therefore, we can use it for processing the validation errors:

因此,我们可以用它来处理验证错误。

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
  MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}

We specified the MethodArgumentNotValidException exception as the exception to be handled. Consequently, Spring Boot will call this method when the specified User object is invalid.

我们指定MethodArgumentNotValidException异常作为要处理的异常。因此,Spring Boot将在指定的User对象无效时调用该方法

The method stores the name and post-validation error message of each invalid field in a Map. Next it sends the Map back to the client as a JSON representation for further processing.

该方法将每个无效字段的名称和验证后的错误信息存储在Map中。接下来,它将Map作为JSON表示法送回客户端,以便进一步处理。

Simply put, the REST controller allows us to easily process requests to different endpoints, validate User objects, and send the responses in JSON format.

简单地说,REST控制器允许我们轻松处理对不同端点的请求,验证User对象,并以JSON格式发送响应。

The design is flexible enough to handle controller responses through several web tiers, ranging from template engines such as Thymeleaf, to a full-featured JavaScript framework such as Angular.

该设计足够灵活,可以通过多个网络层处理控制器响应,从模板引擎(如Thymeleaf)到全功能的JavaScript框架,如Angular

6. Testing the REST Controller

6.测试REST控制器

We can easily test the functionality of our REST controller with an integration test.

我们可以通过集成测试轻松测试我们的REST控制器的功能。

Let’s start mocking/autowiring the UserRepository interface implementation, along with the UserController instance, and a MockMvc object:

让我们开始模拟/自动连接UserRepository接口实现,以及UserController实例和MockMvc 对象。

@RunWith(SpringRunner.class) 
@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {

    @MockBean
    private UserRepository userRepository;
    
    @Autowired
    UserController userController;

    @Autowired
    private MockMvc mockMvc;

    //...
    
}

Since we’re only testing the web layer, we use the @WebMvcTest annotation. It allows us to easily test requests and responses using the set of static methods implemented by the MockMvcRequestBuilders and MockMvcResultMatchers classes.

由于我们只测试Web层,我们使用@WebMvcTest注解。它允许我们使用MockMvcRequestBuildersMockMvcResultMatchers类实现的一组静态方法轻松测试请求和回应。

Now let’s test the addUser() method with a valid and an invalid User object passed in the request body:

现在让我们测试一下addUser()方法,在请求体中传递一个有效的和一个无效的User对象。

@Test
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception {
    MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));
    String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}";
    mockMvc.perform(MockMvcRequestBuilders.post("/users")
      .content(user)
      .contentType(MediaType.APPLICATION_JSON_UTF8))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andExpect(MockMvcResultMatchers.content()
        .contentType(textPlainUtf8));
}

@Test
public void whenPostRequestToUsersAndInValidUser_thenCorrectResponse() throws Exception {
    String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}";
    mockMvc.perform(MockMvcRequestBuilders.post("/users")
      .content(user)
      .contentType(MediaType.APPLICATION_JSON_UTF8))
      .andExpect(MockMvcResultMatchers.status().isBadRequest())
      .andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory")))
      .andExpect(MockMvcResultMatchers.content()
        .contentType(MediaType.APPLICATION_JSON_UTF8));
    }
}

In addition, we can test the REST controller API using a free API life cycle testing application, such as Postman.

此外,我们可以使用免费的API生命周期测试应用程序来测试REST控制器API,例如Postman

7. Running the Sample Application

7.运行示例应用程序

Finally, we can run our example project with a standard main() method:

最后,我们可以用一个标准的main()方法来运行我们的示例项目。

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @Bean
    public CommandLineRunner run(UserRepository userRepository) throws Exception {
        return (String[] args) -> {
            User user1 = new User("Bob", "bob@domain.com");
            User user2 = new User("Jenny", "jenny@domain.com");
            userRepository.save(user1);
            userRepository.save(user2);
            userRepository.findAll().forEach(System.out::println);
        };
    }
}

As expected, we should see a couple of User objects printed out in the console.

正如预期的那样,我们应该看到控制台中打印出几个User对象。

A POST request to the http://localhost:8080/users endpoint with a valid User object will return the String “User is valid”.

向带有有效User对象的http://localhost:8080/users端点发出的POST请求将返回String “User is valid”。

Likewise, a POST request with a User object without name and email values will return the following response:

同样,一个带有User对象的POST请求,如果没有nameemail值,将返回以下响应。

{
  "name":"Name is mandatory",
  "email":"Email is mandatory"
}

8. Conclusion

8.结论

In this article, we learned the basics of performing validation in Spring Boot.

在这篇文章中,我们学习了在Spring Boot中执行验证的基础知识

As usual, all the examples shown in this article are available over on GitHub.

像往常一样,本文中展示的所有例子都可以在GitHub上找到。