gpt4 book ai didi

java - spring InitBinder 是如何工作的?

转载 作者:行者123 更新时间:2023-12-02 05:08:05 27 4
gpt4 key购买 nike

我在网上读到了有关 InitBinder 的内容,但不太清楚它是如何工作的。据我了解,它可以用来执行横切关注诸如设置 validator 、将请求参数转换为某些自定义对象等

在网上遇到下面的例子

@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 对象(否则开发人员必须执行此操作(handleMethod)。对吗?

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

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

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

最佳答案

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

通过这样做:

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

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

如果你有

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

然后编辑器将仅应用于第一个参数,因为第二个参数是 String 而不是 Date

关于java - spring InitBinder 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27590170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com