springMVC中的几种日期转换格式:
1、在pojo中添加字段
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday; |
2、在jsp页面中添加input
<label for="">生日:<input type="text" name="birthday" /></label><br /> |
3、在controller层查看 参数user的状态
结论:
针对日期类型,springmvc默认没有做类型转换,因此会报告400错误,我们需要配置日期类型转换器
方法1:
在pojo的成员变量上加注解
@DateTimeFormat
(pattern=
"yyyy-MM-dd"
)
方法2:自定义类型转换器
1、定义转换器
package com.qfedu.springmvc.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class DateConverter implements Converter<String, Date>{
/**
* 将字符串转换成日期格式
*/
@Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
sdf.setLenient(false);//是否宽松解析:默认true
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
|
2、在spring mvc的配置文件中配置转换器
<!-- 配置注解驱动 -->
<mvc:annotation-driven conversion-service="myConversion" />
<!-- 类型转换器 -->
<bean id="myConversion" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.qfedu.springmvc.converter.DateConverter"></bean>
</set>
</property>
</bean> |
方法3:
在controller中添加如下方法
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
} |