SpringBoot#InitBinder

__震惊!!我的天啦,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);
    }
}

  

 

 

 

 

_

 

转载于:https://www.cnblogs.com/luohaonan/p/11268255.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值