显示表单时未调用 Spring @InitBinder =>自定义编辑器未定义 [英] Spring @InitBinder not invoked when showing form => CustomEditors not defined
问题描述
我有以下(简化到骨骼)控制器:
I have following (simplified to the bone) Controller:
@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>
这是我快速创建的控制器,用于测试我在另一个视图控制器上遇到的问题.正如您在 Controller 中看到的,定义了一个 CustomeDateEditor.在我的实际控制人中,这个编辑器工作正常;例如,当您在表单字段中输入 11/01/2010 时,编辑器会很好地将其转换为日期;同样在返回表单时,日期再次很好地转换回字符串.
This is a controller I quickly created to test out an issue I had with another view-controller. As you can see in the Controller a CustomeDateEditor is defined. In my actual controller this editor is working fine; when you enter for instance 11/01/2010 in the form field this is nicely converted into a Date by the editor; also when going back to the form the Date was again nicely converted back to a String.
但是,当我(如在 TestController 中)想在表单上设置默认日期时,这只会在表单字段中显示一个 Date.toString(),而不是使用来自 CustomDateEditor.getAsText() 的返回值!经过一些调试后,我了解到当 RequestMethod == GET 时不会调用我的 InitBinder 方法.这正常吗?
However, when I (as in TestController) want to set a default date on the form then this gets simply displayed a Date.toString() in the form field instead of using the returned value from CustomDateEditor.getAsText()! After some debugging I learned that my InitBinder method is not called when RequestMethod == GET. Is this normal?
我确信我可以通过不使用来解决这个问题
感谢您的帮助,
斯蒂恩
I'm sure I could workaround this by not using
Thanks for your help,
Stijn
推荐答案
使用 @ModelAttribute
在转发到页面之前设置域.
use @ModelAttribute
to setup domain before forwarding to page.
在处理spring时要小心使用new
,它只会在spring上下文之外创建一个新的对象实例,您不能使用任何spring功能(例如web绑定、验证等).
carefully to use new
when you deal with spring, it will just create a new instance of object outside spring context and you cannot use any of spring capability (such as web binding, validation, etc).
示例:
@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(@ModelAttribute yourDomain, final ModelMap map)
在您的域中,您可以使用:
and at your domain you can use :
@DateTimeFormat(pattern="dd/MM/yyyy")
private Date balance = new Date(System.currentTimeMillis());
这篇关于显示表单时未调用 Spring @InitBinder =>自定义编辑器未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!