如果不做特殊处理,springmvc是无法直接将前端输入的日期字符串转化为java.util.Date类型的。下面是两种配置springmvc可以将前端输入的日期字符串转化为java.util.Date类型的方式。
一、当前类有效
二、全局有效
创建CustomDateEdtor类:
在spingmvc.xml文件中配置如下代码:
重启服务器生效。
一、当前类有效
package cn.smallbug.core.web;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
//<1> 实现WebBindingInitializer接口
@Controller
@Scope("prototype")
public class CustomDateEdtor implements WebBindingInitializer {
// <2> 实现 initBinder 方法,添加@InitBinder注解
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
// <3> 定义转换格式
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//true代表允许输入值为空
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
二、全局有效
创建CustomDateEdtor类:
package cn.smallbug.core.web;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
//<1> 实现WebBindingInitializer接口
public class CustomDateEdtor implements WebBindingInitializer {
// <2> 实现 initBinder 方法
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
// <3> 定义转换格式
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//true代表允许输入值为空
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
在spingmvc.xml文件中配置如下代码:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="cn.smallbug.core.web.CustomDateEdtor" />
</property>
</bean>
重启服务器生效。