SpringBoot#InitBinder
阅读原文时间:2023年07月11日阅读:1

__震惊!!我的天啦,OMG!!


1. initBinder对我而言的价值在于,通过传统表单post数据到后端的controller时候,数据类型的自动转换。比如前端页面填写一个日期字符串,通过InitBinder,可以把日期字符串转换为Date对象。避免了手动转化,或者避免java.lang.IllegalArgumentException异常的产生。

2. initBinder放在RestControllerAdvice注解标注的类中,可以对所有控制器起作用。

3. initBinder对post的json没有效果。

4. 可以自定义自己的Editor然后再InitBinder注册,以完成一些操作。


demo:

@InitBinder  
public void InitBinder(WebDataBinder binder) {

    // 前端字符串格式为yyyy-MM-dd HH:mm:ss 将在此转换为Date对象,然后才把转换的值交给控制器  
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    CustomDateEditor dateEditor = new CustomDateEditor(df, true);  
    binder.registerCustomEditor(Date.class, dateEditor);

    // 对前端传来的字符串通过TextEditor进行处理,处理完成后交给控制器  
    binder.registerCustomEditor(String.class, new TextEditor());  
}

_

demo2

import org.springframework.beans.propertyeditors.PropertiesEditor;

public class TextEditor extends PropertiesEditor {
@Override
public void setAsText(String text) throws IllegalArgumentException {
text = //一些业务逻辑
setValue(text);
}
}

_

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章