首页 > 技术文章 > spring mvc自定义数据转换

yangzhilong 2014-05-13 23:13 原文

@InitBinder 
  在controller中注册一个customer protperty editor以解析request中的参数并通过date bind机制与handler method中的参数做绑定。 

@InitBinder
public void initBinder(WebDataBinder binder) {
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
       dateFormat.setLenient(false);
       binder.registerCustomEditor(Date.class, new CustomDateEditor(
              dateFormat, false));
}

Handler method代码如下

   @RequestMapping("/databind")
    public ModelAndView databind1(Date date) {
      …   
   }

访问url http://localhost:8080/springmvc/databind?date=2000-01-02 
通过initbinder中注册的customeDateEditor类型,自动将2000-01-02转换为日期类型 

 

推荐阅读