Spring MVC 自定義資料繫結 報http 406錯誤
阿新 • • 發佈:2019-02-07
前臺時間(如2013-08-12 18:10:23)傳到後臺srpingMVC 進行繫結到javaBean的util.date 時會報資料繫結失敗,不能從String 轉換到Date 型別。
現在我寫了一個自定議資料繫結類
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;
}