How to validate request parameters in Spring Boot?
In Spring Boot, you can validate request parameters using the @Validated and @Valid annotations provided by the Spring framework.
First, you need to add the following dependencies in the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Next, use the @Validated annotation on the method parameters in the Controller class and use the @Valid annotation before the parameters that need to be validated. For example:
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
@RestController
@Validated
public class UserController {
@PostMapping("/users")
public ResponseEntity createUser(@Valid @RequestBody User user) {
// 处理创建用户的逻辑
// ...
}
}
public class User {
@NotBlank(message = "用户名不能为空")
private String username;
// getter和setter方法
// ...
}
In the example above, the @NotBlank annotation is used to validate the username parameter. If the parameter is empty or contains only spaces, a validation exception will be thrown, and the response will contain the corresponding error message.
Additionally, it is also possible to customize validation annotations, for example:
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.Pattern;
import java.lang.annotation.*;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Pattern(regexp = "^[A-Z0-9]{8}$", message = "订单号必须是8位大写字母和数字的组合")
@Documented
public @interface OrderNo {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class Order {
@OrderNo
private String orderNo;
// getter和setter方法
// ...
}
In custom validation annotations, you can use Spring’s @Pattern and other annotations to define basic validation rules, and then combine them with custom validation rules for validations.
This is the method of using Spring Boot to validate request parameters. In actual development, specific validation annotations can be defined and used based on business requirements to ensure the validity of request parameters.