【问题标题】:How spring InitBinder works?Spring InitBinder 是如何工作的?
【发布时间】:2014-12-21 14:15:58
【问题描述】:

我在网上阅读了有关 InitBinder 的信息,但不太清楚它是如何工作的。据我了解,它可用于执行横切 关注设置验证器,将请求参数转换为一些自定义对象等

在网上看到下面的例子

@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

处理方法是

 public void handlerMethod(@RequestParam("date") Date date) {
 }

优点是在 DispatcherServlet 调用 handlerMethod 之前,它会将请求参数转换为 Date 对象(否则 开发人员必须做它的处理方法)。对吧?

我的问题是spring如何知道需要将哪个请求参数转换为Date对象?

假设我的请求字符串是/someHandler/name?user=Brian&userCreatedDate=2011-01-01&code=aaaa-bb-cc

那么 spring 如何知道它必须转换 userCreatedDate 而不是其他两个参数,即代码/用户?

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    它知道根据数据类型应用转换的请求参数。

    通过这样做:

    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    

    您正在为 Date 类型注册编辑器。

    如果你有

    @RequestMapping("/foo")
    public String foo(@RequestParam("date") Date date,
                      @RequestParam("name") String name) {
        // ...
    }
    

    那么编辑器将只应用于第一个参数,因为第二个是String 而不是Date

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-09
      • 2012-10-08
      • 2018-10-15
      • 2023-03-30
      • 1970-01-01
      • 2011-04-01
      • 2015-04-23
      • 2015-06-26
      相关资源
      最近更新 更多