【发布时间】:2013-09-28 21:58:56
【问题描述】:
如何让initBinder() 方法在每次表单加载和提交时启动。此示例负责将日期从 String 转换为 java.util.Date。
在我的 servlet-context.xml 中:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.example.web.ExampleBindingInitializer" />
</property>
</bean>
这是我的 WebBindingInitializer 实现:
public class ExampleBindingInitializer implements WebBindingInitializer {
private ExampleService exampleService;
@Autowired
public ExampleBindingInitializer(ReservationService reservationService) {
this.reservationService = reservationService;
}
public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
我没有在调用 ExampleService 方法的控制器中进行任何修改。我哪里错了?
当我将带有@InitBinder 注释的initBinder() 方法放入我的控制器时,一切正常。这不满足我,因为我想在外部课程中拥有它。
【问题讨论】:
-
你能发布接受包含日期的对象的控制器方法吗?
-
实际上是否有效取决于您使用的 Spring 版本。请添加版本。如果您使用的是较新的 spring 版本,则应使用
RequestMappingHandlerAdapter而不是AnnotationMethodHandlerAdapter。
标签: java spring spring-mvc