显示表单=>未定义CustomEditor时未调用Spring @InitBinder


问题内容

我有以下(简化为bone)控制器:

@Controller  
public class TestController  {

@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(final ModelMap map) {
    final TestFilter filter = new TestFilter();
    filter.setStartDate(new Date(System.currentTimeMillis()));
    map.addAttribute("reportPerResourceForm", filter);
    return "test";
}

@InitBinder
public void initBinder(final WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
}

}

JSP:

<form:form commandName="reportPerResourceForm" id="reportForm">
    <form:input path="startDate" />
</form:form>

我快速创建了一个控制器,以测试另一个视图控制器遇到的问题。如您在控制器中看到的,定义了CustomeDateEditor。在我的实际控制器中,该编辑器工作正常;当您在表单字段中输入例如11/01/2010时,编辑器会将其很好地转换为日期;当返回表格时,日期也可以很好地转换回字符串。

但是,当我(如在TestController中)想要在表单上设置默认日期时,它将简单地在表单字段中显示Date.toString(),而不是使用CustomDateEditor.getAsText()的返回值!经过一些调试后,我了解到当RequestMethod
== GET时,不会调用我的InitBinder方法。这正常吗?

我确定我可以通过不使用来解决此问题

感谢您的帮助,
Stijn


问题答案:

用于@ModelAttribute在转到页面之前设置域。

new在处理spring时要谨慎使用,它只会在spring上下文之外创建一个新的对象实例,并且您不能使用任何spring功能(例如Web绑定,验证等)。

例如:

@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(@ModelAttribute yourDomain, final ModelMap map)

在您的域中,您可以使用:

@DateTimeFormat(pattern="dd/MM/yyyy")
private Date balance = new Date(System.currentTimeMillis());