---
title: "Spring3 mvc controller映射date类型"
author: "一杯白开水w"
date: "2014-08-19T15:29:51Z"
tags: []
categories: ["编程语言"]
slug: "spring3-mvc-controller-date"
draft: false
lastmod: "2014-08-19T15:29:51Z"
id: 2105968
url: "https://wlt2008-com.iteye.com/blog/2105968"
---

spring3　mvc 的controller方法如果有参数会自动映射传入的来的parameter,但是一个date类型的值传进来会被认为是string类型，如果你需要映射至一个date字段，就会报类型不匹配的exception.如果是spring2.5即需通过extends simpleFormController　override　initBinder方法，注册一个自定义的CustomEditor.但spring3里，这个simpleformController被@Deprecated了，取而代之的是注解的方式即：

```
@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			CustomDateEditor editor = new CustomDateEditor(df, false);
			binder.registerCustomEditor(Date.class, editor);
	}
```

 

将这段代码放在controller里，就可以将2011-02-10 12:34:12这样格式的string转换成date类型的数据了。