亲宝软件园·资讯

展开

SpringBoot注解

羁客% 人气:0

一.添加依赖

<!-- spring-boot 2.3及以上的版本只需要引入下面的依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

二.在类中使用验证注解

1.创建验证实体类(嵌套使用)

@Data
public class UserDto{
 
    @NotBlank(message = "请输入用户名称")
    private String userName;
 
    @NotBlank(message = "请正确输入密码")
    @Length(min = 6,max = 18)
    private String password;
 
    @Email(message = "请正确输入邮箱")
    private String email;
 
 
    @Valid
    @NotEmpty(message = "角色不能为空")
    private List<RoleDto> roleDtos;
 
}
//被嵌套的类
@Data
public class roleDto{
 
    @NotNull(message = "角色ID不能为空")
    private Integer roleId;
 
    @NotBlank(message = "请输入角色名称")
    private String roleName;
 
    @NotBlank(message = "请输入角色名称")
    private String roleCode;
 
    private String desc;
}

2.创建全局异常处理器,对message信息进行处理,并返回给前端

@Component
@Slf4j
public class GlobalValidHandler implements HandlerExceptionResolver {
 
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        String errorMsg;
        if (ex instanceof BindException) {
        //对于验证注解在实体类的属性中的异常处理
            BindException bex = (BindException) ex;
            errorMsg = Objects.requireNonNull(bex.getBindingResult().getFieldError()).getDefaultMessage();
        } else if (ex instanceof ConstraintViolationException) {
        //对于验证注解直接在方法参数中使用的异常处理
            ConstraintViolationException cve = (ConstraintViolationException) ex;
            errorMsg = cve.getMessage();
            if (errorMsg != null) {
                errorMsg = errorMsg.substring(errorMsg.indexOf(": ") + 2);
            }
        } else {
        //其他
            errorMsg = ex.getMessage();
        }
        modelAndView.addObject("msg", errorMsg);
        modelAndView.addObject("code", HttpServletResponse.SC_BAD_REQUEST);
        return modelAndView;
    }
}

3.在controller中的使用

@RestController
@RequestMapping("/user")
public class UserController{
 
    @Autowired
    private UserService userService;
 
    @PostMapping("/add")
    public ApiResult addUser(@Valid @RequsetBody UserDto userDto){
        return ApiResult.data(userService.addUser(userDto));
    }
}

三.在方法参数中使用验证注解,与@RequsetParam注解同时使用,注意类上使用@Validated

@Validated
@RestController
@RequestMapping("/user")
public class UserController{
 
 @Autowired
 private UserSerivce userService;
 
 @GetMapping("/list")
 public ApiResult queryUsers(@RequestParam(name="userName", required = false, defaultValue = "")
                 @NotBlank(message = "请输入用户") String userName,
                 @RequestParam(name="pageNumber", required = false, defaultValue = 1) Integre pageNumber,
                 @RequestParam(name="pageSize", required = false, defaultValue = 10) Integre pageSize){
    return ApiResult.Data(userService.queryUsers(userName,pageNumber,pageSize));
 }
}

ps: 需要在全局变量中对验证注解进行异常处理 GlobalValidHandler

四.自定义验证注解

1.定义验证注解

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidtor.class)
public @interface MyValidator {
 
    String message() default "校验未通过";
 
    Class<?>[] groups() default {};
 
    Class<? extends Payload>[] payload() default {};
}

2.实现验证注解的具体验证逻辑

public class MyConstraintValidator  implements ConstraintValidator<MyValidator, Object> {
    @Override
    public void initialize(MyValidator validator) {
        ConstraintValidator.super.initialize(validator);
    }
 
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        //具体校验逻辑
        //........
        //........
 
        //举个例 验证不为空
        return !ObjectUtils.isEmpty(value);
    }
}

3.使用

@Data
public class UserDto{
 
    @NotNull(message="用户名不能为空")
    private String userName;
 
    @MyValidator(message="密码不能为空")
    private String password;
}

加载全部内容

相关教程
猜你喜欢
用户评论