描述:今天做一個業務操作的時候,ajax傳遞參數要controller出現了400,前后台都沒有報錯。
問題:springmvc 在接收日期類型參數時,如不做特殊處理 會出現400語法格式錯誤
解決:使用SpringMvc進行全局日期處理
案例如下:
1.Controller
/**
* 接收日期類型參數
* 注意:
* springmvc 在接收日期類型參數時,如不做特殊處理 會出現400語法格式錯誤
* 解決辦法
* 1.全局日期處理
*
*/
@RequestMapping("/test")
public String test(Date birthday){
System.out.println(birthday);
return "index";
}
2.自定義類型轉換規則
SpringMvc提供了Converter接口,它支持從一個Object轉換為另一個Object
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
/**
* 全局日期處理類
* Convert<T,S>
* 泛型T:代表客戶端提交的參數 stringDate
* 泛型S:通過convert轉換的類型
通過convert轉換的類型
*/
public class DateConvert implements Converter<String, Date> {
@Override
public Date convert(String stringDate) {
SimpleDateFormat simpleDateFormat =null;
if(stringDate.length()==10) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
else if(stringDate.length()>10)
{
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
return simpleDateFormat.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
3.注冊自定義的類型轉換類
<mvc:annotation-driven conversion-service="conversionService"> <!-- 改寫@ResponseBody的返回值, 此處禁用Jackson序列化空對象報異常的特性 --> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.cn.xf.common.ArcJacksonObjectMapper"> </bean> </property> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 第二步: 創建convertion-Service ,並注入dateConvert--> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="dateConvert"/> </set> </property> </bean> <!-- 第一步: 創建自定義日期轉換規則 --> <bean id="dateConvert" class="com.cn.xf.common.DateConvert"/>
