@Valid 参数校验不生效问题解决

@Valid 参数校验不生效问题解决

  • 问题现象
  • 手动检查

问题现象

import lombok.Data;

import javax.validation.constraints.NotNull;

@Data
public class IDDTO {

    @NotNull
    private Long id;
}
@Slf4j
@Controller
@RequestMapping("/example")
public class ExampleController {

    @POSTMapping(value = "/valid")
    public BaseResponseVO valid(@Valid IDDTO idDTO, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("what fuck");
        }
        return BaseResponseVO.success();
    }

}

看起来像不像会打印what fuck,实际上居然不会。实际上是因为Valid Property 会在json序列化构建Java Bean的时候,所以这里的Post请求还必须是application/json 即:

    @POSTMapping(value = "/valid")
    public BaseResponseVO valid(@Valid @RequestBody IDDTO idDTO, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("what fuck");
        }
        return BaseResponseVO.success();
    }

手动检查

如果有其他情况发现@Valid不生效,提供一个手动检查的方案

import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ValidateUtil {
    private static Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    public static void beanValidate(Object obj) {
        Map<String, String> validatedMsg = new HashMap<>();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
        for (ConstraintViolation<Object> c : constraintViolations) {
            validatedMsg.put(c.getPropertyPath().toString(), c.getMessage());
        }
        if (CollectionUtils.isNotEmpty(constraintViolations)) {
            throw new Exception(validatedMsg);
        }

    }

}

即:

@Slf4j
@Controller
@RequestMapping("/example")
public class ExampleController {

    @POSTMapping(value = "/valid")
    public BaseResponseVO valid(IDDTO idDTO){
        ValidateUtil.beanValidate(idDTO);
        return BaseResponseVO.success();
    }

}

你可能感兴趣的:(Java,java,spring)