7.13 在SpringBoot中 正确使用Validation实现参数效验
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
public class UserController {
@PostMapping("/user")
public String createUser(@RequestBody @Valid UserDto userDto) {
// 逻辑处理
return "User created";
}
}
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import javax.validation.groups.Default;
public class UserDto {
@NotBlank(groups = Default.class, message = "用户名不能为空")
@Size(min = 3, max = 60, groups = Default.class, message = "用户名长度必须在3到60个字符之间")
private String username;
@NotBlank(groups = Default.class, message = "密码不能为空")
@Size(min = 6, max = 200, groups = Default.class, message = "密码长度必须在6到200个字符之间")
private String password;
@Email(groups = Default.class, message = "邮箱格式不正确")
private String email;
// 省略getter和setter方法
}
这个代码实例展示了如何在Spring Boot中使用@Validated
注解和JSR-380(Hibernate Validator)中的注解来对传入的UserDto对象进行验证。如果验证失败,Spring会自动抛出MethodArgumentNotValidException
异常,并且可以配置全局异常处理来返回一个更友好的错误响应。
评论已关闭