|
对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
DataBinder
@Controller或@ControllerAdvice类可以有@InitBinder方法,设置为
初始化WebDataBinder.反过来,这些用于:
-
将请求参数(即表单数据或查询)绑定到模型对象。
-
转换
String-based 请求值(例如请求参数、路径变量、headers、cookie 等)添加到控制器方法参数的目标类型。 -
将模型对象值格式化为
String呈现 HTML 表单时的值。
@InitBinder方法可以注册特定于控制器java.beans.PropertyEditor或 SpringConverter和Formatter组件。 此外,您可以使用 WebFlux Java 配置进行注册Converter和Formatter全局共享的类型FormattingConversionService.
@InitBinder方法支持许多相同的参数@RequestMapping方法 do,但@ModelAttribute(命令对象)参数。通常,它们被声明为带有WebDataBinder参数,用于注册,以及void返回值。以下示例使用@InitBinder注解:
-
Java
-
Kotlin
@Controller
public class FormController {
@InitBinder (1)
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// ...
}
| 1 | 使用@InitBinder注解。 |
@Controller
class FormController {
@InitBinder (1)
fun initBinder(binder: WebDataBinder) {
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
dateFormat.isLenient = false
binder.registerCustomEditor(Date::class.java, CustomDateEditor(dateFormat, false))
}
// ...
}
| 1 | 使用@InitBinder注解。 |
或者,当使用Formatter通过共享的基于设置FormattingConversionService,您可以重复使用相同的方法并注册特定于控制器Formatter实例,如以下示例所示:
-
Java
-
Kotlin
@Controller
public class FormController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); (1)
}
// ...
}
| 1 | 添加自定义格式化程序(DateFormatter,在本例中)。 |
@Controller
class FormController {
@InitBinder
fun initBinder(binder: WebDataBinder) {
binder.addCustomFormatter(DateFormatter("yyyy-MM-dd")) (1)
}
// ...
}
| 1 | 添加自定义格式化程序(DateFormatter,在本例中)。 |