SpringMVC:带参请求或者Form表单请求参数校验(NotNull,NotEmtry)

1、编写校验工具类

@Slf4j
public class ParamVerifyUtils {

    private static volatile Validator validator;

    public static void verifyParams(BindingResult result) throws InvalidParamException {
        if (result.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            List fieldErrorList =result.getFieldErrors();
            for(FieldError fieldError : fieldErrorList){
                log.error("verifyParams error --> " + fieldError.getField());
                log.error("verifyParams message --> " + fieldError.getDefaultMessage());
                stringBuilder.append("<" + fieldError.getField() + "[" + fieldError.getDefaultMessage() + "]>");
            }
            throw new InvalidParamException("(" + stringBuilder + ")");
        }
    }
}

2、controller demo

@PostMapping(value = "/test")
    public BaseResponse test(@Valid ToBAlarmRequest toBAlarmRequest, BindingResult result) throws Exception {
        ParamVerifyUtils.verifyParams(result);
        return testService.test(toBAlarmRequest);
    }

注意:@Valid 这个一定要加上,不然会没有校验

BindingResult result 这个也要带上 这个是校验结果

你可能感兴趣的:(SpringMVC,笔记)