前台时间(如2013-08-12 18:10:23)传到后台srpingMVC 进行绑定到javaBean的util.date 时会报数据绑定失败,不能从String 转换到Date 类型。
这里我们无非就是想办法进行数据类型转换和绑定。具体绑定参见:http://aokunsang.iteye.com/blog/1409505 这位博主总结得很到位。
现在我写了一个自定议数据绑定类
package com.ltkj.zhepg.com.util;
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;
/**
* pring3 mvc 的日期传递[前台-后台]bug:
* org.springframework.validation.BindException
* 的解决方式.包括xml的配置
* @author ZOUKANG http://blog.csdn.net/kang89/
*/
public class SpringDateConverter implements WebBindingInitializer {
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(df,true));
}
}
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<!-- 日期格式转换 -->
<property name="webBindingInitializer">
<bean class="com.ltkj.zhepg.com.util.SpringDateConverter" />
</property>
</bean>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <!-- 这个类里面你可以注册拦截器什么的 --> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="com.ltkj.zhepg.com.util.SpringDateConverter" /> <!-- 这里注册自定义数据绑定类 --> </property> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter" /> <!-- 注册JSON Converter --> </list> </property> </bean> <mvc:annotation-driven />
上面原因就在转为json没有显式声明。之前没有报406是因为没有使用自定义的转换器,json转换也采用了默认的了,所有没有这个406错误
@RequestMapping(value="/add", method=RequestMethod.POST)
public @ResponseBody Map<String, String> addCustomer( NotifyInfo notifyInfo, HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>(1);
try {
if(notifyInfo.getContent() != null) {
this.notifyInfoService.addOrUpdate(notifyInfo);
}
map.put(AJAX_MESSAGE, "true");
} catch (ApplyException e) {
map.put(AJAX_MESSAGE, "false");
}
return map;
}