简体   繁体   English

Spring InitBinder如何工作?

[英]How spring InitBinder works?

I read about InitBinder on net but not very clear how it works. 我在网上阅读了有关InitBinder的信息,但不清楚其工作原理。 As per my understanding it can be used to perform cross cutting concern like setting validator, conversion of request parameter to some custom object etc 根据我的理解,它可以用于执行交叉关注,例如设置验证器,将请求参数转换为某些自定义对象等

Came across below example on net 在网上遇到了以下示例

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

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

Handler method is 处理程序方法是

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

The advantage is before DispatcherServlet calls the handlerMethod it converts the request parameter in to Date object (otherwise developer has to do it handleMethod). 好处是,在DispatcherServlet调用handlerMethod之前,它将请求参数转换为Date对象(否则开发人员必须将它作为handleMethod)。 Right? 对?

My question how spring knows which request parameter needs to be converted to Date object? 我的问题是spring如何知道哪个请求参数需要转换为Date对象?

Say my request string is /someHandler/name?user=Brian&userCreatedDate=2011-01-01&code=aaaa-bb-cc 说我的请求字符串是/someHandler/name?user=Brian&userCreatedDate=2011-01-01&code=aaaa-bb-cc

So how spring knows it has to convert userCreatedDate not other two parameters ie code/user? 那么spring如何知道它必须转换userCreatedDate而不是其他两个参数,即code / user?

It knows which request parameters to apply the conversion to based on their datatype. 它知道基于数据类型将转换应用于哪些请求参数。

By doing this: 通过做这个:

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

You are registering the editor for the Date type. 您正在为Date类型注册编辑器。

So if you have 所以如果你有

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

Then the editor will be applied only to the first parameter, because the second one is String not Date . 然后,编辑器将仅应用于第一个参数,因为第二个参数是String而不是Date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM