在springmvc中,我們會經常用到它的自動綁定參數,綁定日期時時常會報400的錯誤→ Bad Request(
請求出錯,由于文法格式有誤,伺服器無法了解此請求。不作修改,客戶程式就無法重複此請求).
廢話不多說,直接上代碼,
解決方法有很多:
第一種:需要将DateFormatter注冊到一個ConversionService中,最後再将ConversionService注冊到Spring MVC中:
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="com.sfbf.util.DateFormatter"></bean>
</set>
</property>
</bean>
我在背景寫了個DateFormatter實作Formatter<Date>接口:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.format.Formatter;
public class DateFormatter implements Formatter<Date> {
@Override
public String print(Date arg0, Locale arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Date parse(String text, Locale locale) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
if(!"".equals(text)&&null!=text)
date = format.parse(text);
} catch (Exception e) {
format = new SimpleDateFormat("yyyy-MM-dd");
date = format.parse(text);
}
return date;
}
}
第二種方法:可以直接在方法上添加注解 @ResponseBody 傳回JSON資料,如果javabean的屬性中包含 Date日期類型的資料:
像我之前寫的部落格那樣http://blog.csdn.net/u012169499/article/details/45026411
寫個JsonDateSerializer來讓它繼承JsonSerializer,然後在相應的實體的屬性方法上添加指定注解:@JsonSerialize 即可實作.