SpringBoot进行参数校验的方法详解
一、为什么需要参数校验?
在实际开发中,我们常常需要对一些参数进行校验,防止参数不合法导致程序出错。比如在登录界面中,用户名和密码不能为空,当用户输入的用户名密码为空时,我们需要提示用户输入正确的用户名和密码。如果没有对参数进行校验,程序会直接抛出空指针异常,这是非常不可取的。
二、SpringBoot参数校验的方式
SpringBoot提供了多种方式来进行参数校验,下面我们将详细介绍两种常用的方式。
1.注解方式
在实体类中使用注解来完成参数校验。具体步骤如下:
1.在实体类中添加注解@javax.validation.constraints,例如:
public class User{
@NotBlank(message = "用户名不能为空")
private String username;
@NotBlank(message = "密码不能为空")
private String password;
}
2.使用@Valid注解在Controller层对参数进行校验,例如:
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public String login(@Valid @RequestBody User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return bindingResult.getAllErrors().toString();
}
return "login";
}
}
2.自定义校验注解
我们也可以通过自定义注解来进行参数校验,具体步骤如下:
1.自定义注解,例如:
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface Password {
String message() default "密码必须由6-16位数字或字母组成";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
2.定义校验器PasswordValidator,例如:
public class PasswordValidator implements ConstraintValidator<Password, String> {
@Override
public void initialize(Password constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
Pattern pattern = Pattern.compile("^[a-zA-Z0-9]{6,16}$");
Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
}
3.在实体类中使用自定义注解,例如:
public class User{
@NotBlank(message = "用户名不能为空")
private String username;
@Password
private String password;
}
4.使用@Valid注解在Controller层对参数进行校验,例如:
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public String login(@Valid @RequestBody User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return bindingResult.getAllErrors().toString();
}
return "login";
}
}
三、示例
下面我们通过示例来演示使用注解和自定义注解的方式进行参数校验。
1.注解方式示例
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public String login(@Valid @RequestBody User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return bindingResult.getAllErrors().toString();
}
return "login";
}
}
调用POST接口{{host}}/user/login,传入json参数:
{
"username": "",
"password": ""
}
则返回结果为:
[{"codes":["NotBlank.user.username","NotBlank.username","NotBlank.java.lang.String","NotBlank"],"arguments":[{"codes":["user.username","username"],"arguments":null,"defaultMessage":"username","code":"username"},{"defaultMessage":"Default","codes":["javax.validation.constraints.NotBlank.message","NotBlank.message","javax.validation.constraints.NotBlank"],"arguments":null,"code":"NotBlank"}],"defaultMessage":"用户名不能为空","objectName":"user","field":"username","rejectedValue":"","bindingFailure":false,"code":"NotBlank"}]
2.自定义注解方式示例
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/register")
public String register(@Valid @RequestBody RegisterForm registerForm, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return bindingResult.getAllErrors().toString();
}
return "register";
}
}
自定义注解@Phone和校验器PhoneValidator:
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PhoneValidator.class)
@Documented
public @interface Phone {
String message() default "手机号格式不正确";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
public class PhoneValidator implements ConstraintValidator<Phone, String> {
@Override
public void initialize(Phone constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
Pattern pattern = Pattern.compile("^[1][3-9][0-9]{9}$");
Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
}
RegisterForm实体类:
public class RegisterForm {
@NotBlank(message = "用户名不能为空")
private String username;
@NotBlank(message = "密码不能为空")
private String password;
@Phone
private String phone;
}
调用POST接口{{host}}/user/register,传入json参数:
{
"username": "user1",
"password": "123456",
"phone": "12345678900"
}
则返回结果为:
"register"
如果传入json参数:
{
"username": "user2",
"password": "123456",
"phone": "1234567890"
}
则返回结果为:
[{"codes":["Phone.registerForm.phone","registerForm.phone","phone","java.lang.String","Phone"],"arguments":[{"codes":["registerForm.phone","phone"],"arguments":null,"defaultMessage":"phone","code":"phone"},{"defaultMessage":"Default","codes":["amethyst.constraint.Phone.message","Phone.message","javax.validation.constraints.Pattern.message","javax.validation.constraints.Pattern"],"arguments":null,"code":"Phone"}],"defaultMessage":"手机号格式不正确","objectName":"registerForm","field":"phone","rejectedValue":"1234567890","bindingFailure":false,"code":"Phone"}]
以上就是SpringBoot进行参数校验的详细攻略,希望对大家有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot进行参数校验的方法详解 - Python技术站