1. Introduction
1.绪论
In this tutorial, we’ll learn how to validate HTTP request parameters and path variables in Spring MVC.
在本教程中,我们将学习如何在Spring MVC中验证HTTP请求参数和路径变量。
Specifically, we’ll validate String and Number parameters with JSR 303 annotations.
具体来说,我们将用JSR 303注释来验证String和Number参数。
To explore the validation of other types, we can refer to our tutorials about Java Bean Validation and method constraints, or we can learn how to create our own validator.
要探索其他类型的验证,我们可以参考我们关于Java Bean验证和method constraints的教程,或者我们可以学习如何创建我们自己的验证器。
2. Configuration
2.配置
To use the Java Validation API, we have to add a JSR 303 implementation, such as hibernate-validator:
为了使用Java验证API,我们必须添加一个JSR 303实现,例如hibernate-validator。
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
We also have to enable validation for both request parameters and path variables in our controllers by adding the @Validated annotation:
我们还必须通过添加@Validated annotation,在控制器中启用对请求参数和路径变量的验证。
@RestController
@RequestMapping("/")
@Validated
public class Controller {
// ...
}
It’s important to note that enabling parameter validation also requires a MethodValidationPostProcessor bean. If we’re using a Spring Boot application, then this bean is auto-configured, as we have the hibernate-validator dependency on our classpath.
值得注意的是,启用参数验证还需要一个MethodValidationPostProcessor Bean。如果我们使用的是Spring Boot应用程序,那么这个Bean就是自动配置的,因为我们的classpath上有hibernate-validator的依赖。
Otherwise, in a standard Spring application, we have to add this bean explicitly:
否则,在一个标准的Spring应用程序中,我们必须明确地添加这个Bean。
@EnableWebMvc
@Configuration
@ComponentScan("com.baeldung.spring")
public class ClientWebConfigJava implements WebMvcConfigurer {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
// ...
}
By default, any error during path or request validation in Spring results in an HTTP 500 response. In this tutorial, we’ll use a custom implementation of ControllerAdvice to handle these kinds of errors in a more readable way, returning an HTTP 400 for any bad request. We can find the source code of this solution at GitHub.
默认情况下,Spring中路径或请求验证过程中的任何错误都会导致HTTP 500响应。在本教程中,我们将使用ControllerAdvice的自定义实现,以更可读的方式处理此类错误,对任何不良请求返回HTTP 400。我们可以在GitHub.找到这个解决方案的源代码。
3. Validating a RequestParam
3.验证一个RequestParam
Let’s consider an example where we pass a numeric weekday into a controller method as a request parameter:
让我们考虑一个例子,我们将一个数字的工作日作为请求参数传入控制器方法。
@GetMapping("/name-for-day")
public String getNameOfDayByNumber(@RequestParam Integer dayOfWeek) {
// ...
}
Our goal is to make sure that the value of dayOfWeek is between 1 and 7. To do so, we’ll use the @Min and @Max annotations:
我们的目标是确保dayOfWeek的值在1到7之间。为此,我们将使用@Min和@Max注释。
@GetMapping("/name-for-day")
public String getNameOfDayByNumber(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {
// ...
}
Any request that doesn’t match these conditions will return an HTTP status 400 with a default error message.
任何不符合这些条件的请求将返回HTTP状态400,并带有默认错误信息。
If we call http://localhost:8080/name-for-day?dayOfWeek=24, for instance, the response message will be:
例如,如果我们调用http://localhost:8080/name-for-day?dayOfWeek=24,响应信息将是。
getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7
We can change the default message by adding a custom one:
我们可以通过添加一个自定义的信息来改变默认的信息。
@Max(value = 1, message = “day number has to be less than or equal to 7”)
4. Validating a PathVariable
4.验证一个PathVariable
Just as with @RequestParam, we can use any annotation from the javax.validation.constraints package to validate a @PathVariable.
就像@RequestParam一样,我们可以使用javax.validation.constraints包中的任何注解来验证@PathVariable。
Let’s consider an example where we validate that a String parameter isn’t blank and has a length of less than or equal to 10:
让我们考虑一个例子,我们验证一个字符串参数不是空白的,并且长度小于或等于10。
@GetMapping("/valid-name/{name}")
public void createUsername(@PathVariable("name") @NotBlank @Size(max = 10) String username) {
// ...
}
Any request with a name parameter longer than 10 characters, for instance, will result in an HTTP 400 error with a message:
例如,任何带有name参数超过10个字符的请求,都会导致HTTP 400错误,并附有信息。
createUser.name:size must be between 0 and 10
The default message can be easily overwritten by setting the message parameter in the @Size annotation.
通过在@Size注解中设置message参数,可以很容易地覆盖默认信息。
5. Conclusion
5.总结
In this article, we learned how to validate request parameters and path variables in Spring applications.
在这篇文章中,我们学习了如何在Spring应用程序中验证请求参数和路径变量。
As always, all source code is available on GitHub.
一如既往,所有源代码都可以在GitHub上找到。