自定义springMVC的属性编辑器主要有两种方式:
一种是使用@InitBinder标签在运行期注册一个属性编辑器,这种编辑器只在当前Controller里面有效;
另一种是实现自己的 WebBindingInitializer,然后定义一个AnnotationMethodHandlerAdapter的bean,在此bean里面进行注册
第一种方式:
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/qt")
public class QtController {
// 日期字符串转Date
public static Date dateStr2date(String dateStr) {
dateStr = dateStr.replaceAll("-", " ").replaceAll(":", " ");
String newTimeStr = "";
String[] dateStrArray = dateStr.split(" ");
int[] timeArray = { 1, 1, 1, 0, 0, 0 };
for (int i = 0; i < dateStrArray.length; i++) {
if (i < 6) {
timeArray[i] = Integer.valueOf(dateStrArray[i]);
}
}
newTimeStr = String.format("%s-%s-%s %s:%s:%s", timeArray[0], timeArray[1], timeArray[2], timeArray[3], timeArray[4], timeArray[5]);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sdf.parse(newTimeStr);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
// Date转字符串
public static String date2dateStr(Date date) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public String getAsText() {
return date2dateStr((Date) getValue());
}
@Override
public void setAsText(String text) {
setValue(dateStr2date(text));
}
});
}
}
第二种方式:
1.定义自己的WebBindingInitializer
package com.xxx.blog.util;
import java.util.Date;
import java.text.SimpleDateFormat;
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;
public class MyWebBindingInitializer implements WebBindingInitializer {
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
// TODO Auto-generated method stub
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
}
2.在springMVC的配置文件里面定义一个AnnotationMethodHandlerAdapter,并设置其WebBindingInitializer属性为我们自己定义的WebBindingInitializer对象
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0"/>
<property name="webBindingInitializer">
<bean class="com.xxx.blog.util.MyWebBindingInitializer"/>
</property>
</bean>