spring mvc自己主动日期格式化绑定
在springmvc中,我们会经经常使用到它的自己主动绑定參数,绑定日期时时常会报400的错误→Bad
Request(
请求出错,因为语法格式有误,server无法理解此请求。不作改动,客户程序就无法反复此请求).
废话不多说,直接上代码,
解决方法有非常多:
第一种:须要将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 就可以实现.

浙公网安备 33010602011771号