1:
注册Controller内的Binder:
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// true:允许输入空值,false:不能为空值 }
2:或注册全局的binder:
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" /> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <constructor-arg index="0"> <util:constant static-field="com.systoon.smvc.utils.json.JsonUtils.OBJECT_MAPPER"/> </constructor-arg> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> <!-- 注册自定义转换器 --> <property name="webBindingInitializer"> <bean class="com.systoon.smvc.converter.SpringMVCConverter"> <property name="datePattern" value="yyyy-MM-dd HH:mm:ss,yyyy-MM-dd"/> </bean> </property> </bean> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.systoon.advice.web.*.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 注意放到最后,否则全局binder不起作用 --> <mvc:annotation-driven />
以上的:<mvc:annotation-driven /> 必须放到最后,否则全局binder不起作用!!!!!