一、当前类有效
package cn.smallbug.core.web; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; //<1> 实现WebBindingInitializer接口 @Controller @Scope("prototype") public class CustomDateEdtor implements WebBindingInitializer { // <2> 实现 initBinder 方法,添加@InitBinder注解 @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { // <3> 定义转换格式 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //true代表允许输入值为空 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
二、全局有效
创建CustomDateEdtor类:
package cn.smallbug.core.web; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; //<1> 实现WebBindingInitializer接口 public class CustomDateEdtor implements WebBindingInitializer { // <2> 实现 initBinder 方法 @Override public void initBinder(WebDataBinder binder, WebRequest request) { // <3> 定义转换格式 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //true代表允许输入值为空 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
在spingmvc.xml文件中配置如下代码:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="cn.smallbug.core.web.CustomDateEdtor" /> </property> </bean>
重启服务器生效。