spring mvc使用@InitBinder 标签将日期格式字符串转换成Timestamp类型

在SpringMVC中,可以采用实体类来自动绑定表单传递过来的参数,但需要注意的是,若实体类属性是Date或Timestamp类型的话,SpringMVC将无法自动绑定,会产生400错误,所以需要我们自定义转换规则。

方法:

1.定义转换规则:创建编辑器类,继承自PropertiesEditor(由Spring提供)

    import java.sql.Timestamp;
    import org.springframework.beans.propertyeditors.PropertiesEditor;

    public class TimestampEditor extends PropertiesEditor {
@Override

public void setAsText(String text) throws IllegalArgumentException {

                //note:只能将 yyyy-MM-dd HH:mm:ss或者yyyy-M-d HH:mm:ss格式的字符串进行转换

                             yyyy-MM-dd是不可以的

setValue(Timestamp.valueOf(text));

}

@Override
public String getAsText() {
return getValue().toString();
}
    }

2.应用转换规则:在Controller中添加initBinder方法,并在方法上添加Spring提供的@InitBinder注解

    import org.springframework.web.bind.annotation.InitBinder;
    @Controller

    public class WebController {

        @RequestMapping("/test.do")

@ResponseBody

public String test(User u){ //note:User为接收参数的实体类

return "OK";
}
@InitBinder
public void initBinder(WebDataBinder binder){
   binder.registerCustomEditor(Timestamp.class, new TimestampEditor());  
}
    }


完成上述两个步骤以后,当请求参数传递过来时,Spring就会先调用initBinder方法对请求参数进行转换,然后再将参数绑定到实体类对象上。

    

    


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值