使用注解验证字段(@Validated)

我们在日常开发中经常会使用 if 语句来判断请求参数,如果要判断的参数较多,会造成大面积代码都在写判断,“实际业务三行,条件判断三十行”,哈哈,开玩笑

常用方式

...
if (StringUtils.isBlank(xxx1)) {
      return ServerResponse.createByErrorMessage("xxx1不能为空");
}
if (StringUtils.isBlank(xxx2)) {
      return ServerResponse.createByErrorMessage("xxx2不能为空");
}
if (StringUtils.isBlank(xxx3)) {
      return ServerResponse.createByErrorMessage("xxx3不能为空");
}
...

简洁的注解验证方式

写个小例子来演示一下

实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestEntity implements Serializable {

    @NotBlank(message = "name不能为空")
    private String name;

    @NotBlank(message = "add不能为空")
    private String add;

    @NotBlank(message = "phone不能为空")
    private String phone;
}
实现方式
@SpringBootApplication
@RestController
public class DemotestApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemotestApplication.class, args);
    }

    /**
     * 使用注解验证字段
     */
    @PostMapping("/test")
    public ServerResponse test(@Validated TestEntity testEntity, BindingResult br) {
        if (br.hasErrors()) {
            // br.getFieldError().getDefaultMessage():获取错误信息
            return ServerResponse.createByErrorMessage(br.getFieldError().getDefaultMessage());
        }
        return ServerResponse.createBySuccess(testEntity);
    }

}
使用postman测试

在这里插入图片描述
注:文中的ServerResponse类是用于前后端传递的工具类,百度上很多~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Spring 框架中的 @Validated 注解时,可以通过分组(groups)来对验证进行分类和组织。这种分组功能允许您根据不同的验证场景来选择性地进行验证。 以下是一个示例,演示了如何在Spring中使用 @Validated 注解和分组: ```java import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.groups.Default; // 定义分组接口 public interface Group1 { } public interface Group2 { } // 定义验证类 @Validated public class UserValidator { public void validateGroup1(@NotNull(groups = Group1.class) Integer id, @NotBlank(groups = Group1.class) String name) { // 针对 Group1 进行的验证逻辑 } public void validateGroup2(@NotBlank(groups = Group2.class) String email, @NotBlank(groups = Group2.class) String password) { // 针对 Group2 进行的验证逻辑 } public void validateDefaultGroup(@NotBlank String username) { // 针对 Default 分组进行的验证逻辑 } } ``` 在上述示例中,我们定义了两个分组接口:Group1 和 Group2。然后,在 UserValidator 类中,我们使用 `@NotNull(groups = Group1.class)` 和 `@NotBlank(groups = Group1.class)` 注解来指定在 Group1 分组中需要验证字段。同样地,我们使用 `@NotBlank(groups = Group2.class)` 注解来指定在 Group2 分组中需要验证字段。 接着,我们可以在业务逻辑中根据需要调用不同的验证方法,例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @Service @Validated public class UserService { private final UserValidator userValidator; @Autowired public UserService(UserValidator userValidator) { this.userValidator = userValidator; } public void createUser(@NotNull(groups = Group1.class) Integer id, @NotBlank(groups = Group1.class) String name) { userValidator.validateGroup1(id, name); // 创建用户的逻辑 } public void resetPassword(@NotBlank(groups = Group2.class) String email, @NotBlank(groups = Group2.class) String password) { userValidator.validateGroup2(email, password); // 重置密码的逻辑 } } ``` 在上述示例中,UserService 类使用了 @Validated 注解,用于表示该类中的方法参数需要进行验证。通过使用 `@NotNull(groups = Group1.class)` 和 `@NotBlank(groups = Group1.class)` 注解指定了在 Group1 分组中需要验证字段。同样地,在 resetPassword 方法中,我们使用 `@NotBlank(groups = Group2.class)` 注解来指定在 Group2 分组中需要验证字段。 这样,当调用 UserService 类中的方法时,Spring 框架会根据不同的分组进行相应的验证。 需要注意的是,默认情况下,Spring 使用 Default 分组(即没有指定任何分组)进行验证。如果没有显式地指定分组,那么使用默认分组进行验证。 希望这个示例能够帮助您理解在Spring中如何使用 @Validated 注解和分组进行验证

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值