简体   繁体   English

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

[英]How to execute code before @InitBinder validation

I have a program that has a functionality to upload a file and then validate if it's name format is correct and save it to db.我有一个程序,它具有上传文件的功能,然后验证它的名称格式是否正确并将其保存到 db。

In my main controller I am using @InitBinder for validation.在我的主控制器中,我使用 @InitBinder 进行验证。

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

In my validator method I am using this code snippet:在我的验证器方法中,我使用了以下代码片段:

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);
        }
    }

What I want to do is, I want to format file name (like replacing some characters in file name) and then use validator class.我想要做的是,我想格式化文件名(比如替换文件名中的一些字符),然后使用验证器类。 Thus I need to change file name before the validation.因此我需要在验证之前更改文件名。

How can I achieve editing file name before validating the format with @InitBinder ?如何在使用@InitBinder验证格式之前实现编辑文件名?

Edit: Noone answers?编辑:没有人回答? Or the question isn't clear ?还是问题不清楚?

Why not use WebDataBinder 's addCustomFormatter like you did for adding a validator ?为什么不像添加验证器那样使用WebDataBinderaddCustomFormatter呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring InitBinder如何工作? - How spring InitBinder works? java的this()构造函数重载,如何在this()之前执行代码 - java Constructor overload with this(), how to execute code before this() 如何在类级别注释之前对用@valid 注释的属性执行验证? - how to execute validation on property annotated with @valid before a class level annotation? 如何编写用于json反序列化的initbinder? - How to write initbinder for json deserialization? 如何确保 CompletableFuture 在执行一段代码之前完全完成? - How to ensure that CompletableFuture is completely finished before execute a piece of code? 如何使在启动时运行的代码在计划之前首先执行? - How to make a code that is run on startup execute first, before scheduled? 如何在恢复代码之前等待setIcon()方法执行? - How to wait for setIcon() method to execute before resuming the code? 如何在其余代码之前执行一行代码? 更改按钮上的文字 - How to execute one line of code before the rest? Changing text on a button 如何使用 swing 定时器等待 1 秒再继续执行代码? - How to use a swing timer to wait 1 second before continuing to execute code? 如何在所有测试类开始之前执行一段代码? - How to execute a piece of code once before all test classes start?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM