如何在@InitBinder验证之前执行代码



>我有一个程序,它具有上传文件的功能,然后验证它的名称格式是否正确并将其保存到数据库。

在我的主控制器中,我正在使用@InitBinder进行验证。

@InitBinder("uploadFileForm")
    protected void initBinderUploadForm(WebDataBinder binder) {
        binder.setValidator(fileNameFormatValidator);
    }

在我的验证器方法中,我使用以下代码片段:

static void validateFileName(String fileUploadKey, MultipartFile file, Errors errors) {
        Matcher validFilenameMatcher = VALID_FILE_NAME.matcher(file.getOriginalFilename());
        if (!validFilenameMatcher.matches()) {
            errors.rejectValue(fileUploadKey, null, null, SOME_REGEX);
        }
    }

我想做的是,我想格式化文件名(比如替换文件名中的一些字符),然后使用验证器类。因此,我需要在验证之前更改文件名。

如何在使用 @InitBinder 验证格式之前实现编辑文件名?

编辑:没有人回答?还是问题不清楚?

为什么不像添加验证器那样使用 WebDataBinder 的 addCustomFormatter?

@InitBinder("uploadFileForm")
protected void initBinderUploadForm(WebDataBinder binder) {
    binder.addCustomFormatter(fileNameFormatter); 
    binder.setValidator(fileNameFormatValidator);
}

最新更新