标签:spring mvc 日期格式化 javabean conversionservice
在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 即可实现.
标签:spring mvc 日期格式化 javabean conversionservice
原文地址:http://blog.csdn.net/u012169499/article/details/46417961