前台时间(如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));
}
}
关在srping 里声明
<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 />
现在数据也能绑定了,但就是ajax 提交后返回http 406 ,半天没有弄懂,后来想到了改为下面的声明配置即可,没有这个406问题
<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 />
附:415 Unsupported Media Type 没有配置<mvc:annotation-driven />转换
406 the server responded with a status of 406 由于客户端请求的MediaType类型默认是:*/*
上面原因就在转为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;
}