Spring Validator參數校驗


Spring Validator參數校驗

Spring提供了Validator接口用於對Bean即一般的接口入參DTO做參數校驗。

校驗器需要實現Validator接口:

@Component //使校驗器可以注入Controller類
public class FeedBackDtoValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(FeedBackDto.class);
    }

    @Override
    public void validate(Object target, Errors errors) {

        FeedBackDto dto=(FeedBackDto)target;

        if(null !=dto.getCourseFeedBackId() && StringUtils.isBlank(EnumCourseFeedStatus.getValue(dto.getCourseFeedBackId()))){

            errors.reject("課堂反饋狀態參數錯誤", "課堂反饋狀態參數錯誤");
            return;
        }

        if(StringUtils.isBlank(dto.getStartDate()) || StringUtils.isBlank(dto.getEndDate())){
            errors.reject("開始和結束日期必須同時選中", "開始和結束日期必須同時選中");
            return;
        }

    }
}
    @InitBinder(value = "feedBackDto")
    public void initBinderParameter(WebDataBinder binder) {
        binder.addValidators(feedBackDtoValidator);
    }

@InitBinder 注解
用於初始化WebDataBinder

WebDataBinder
將請求參數綁定到Java類(Java Bean)

@InitBinder
public void dataBinding(WebDataBinder binder) {
	binder.addValidators(userValidator, emailValidator);
	SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	dateFormat.setLenient(false);
	binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
} 

CustomDateEditor
轉換請求參數格式的工具
registerCustomEditor()
注冊請求參數格式轉換工具

@ApiOperation(value = "查詢課堂反饋列表")
@ResponseBody
@RequestMapping(value = "/feedbackList", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseInfo<Criteria<OCourseFeedbackVO>> feedbackList(@Valid @ApiParam(value = "查詢參數")@RequestBody FeedBackDto feedBackDto, BindingResult result, @RequestHeader("access-token") String token) throws Exception {
    if (result.hasErrors()) {
        throw new CustomExcetion(result.getAllErrors().get(0).getDefaultMessage().toString());
    }
    return buildSuccessRetunInfo();
}

@Valid
Hibernate-Valid 注解,表示開啟入參校驗

BindingResult
校驗結果,如果校驗不成功(result.hasErrors()),則返回校驗失敗。


[1]:Spring MVC 4 - Form validation example using Validator interface
[2]:SR 303 - Bean Validation 介紹及最佳實踐


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM