自定义springMVC的属性编辑器主要有两种方式:
一种是使用@InitBinder标签在运行期注册一个属性编辑器,这种编辑器只在当前Controller里面有效;
另一种是实现自己的 WebBindingInitializer,然后定义一个AnnotationMethodHandlerAdapter的bean,在此bean里面进行注册
第一种方式:
1import java.beans.PropertyEditorSupport; 2import java.text.ParseException; 3import java.text.SimpleDateFormat; 4import java.util.Date; 5 6import org.springframework.stereotype.Controller; 7import org.springframework.web.bind.WebDataBinder; 8import org.springframework.web.bind.annotation.InitBinder; 9import org.springframework.web.bind.annotation.RequestMapping; 10 11@Controller 12@RequestMapping("/qt") 13public class QtController { 14 // 日期字符串转Date 15 public static Date dateStr2date(String dateStr) { 16 dateStr = dateStr.replaceAll("-", " ").replaceAll(":", " "); 17 String newTimeStr = ""; 18 String[] dateStrArray = dateStr.split(" "); 19 int[] timeArray = { 1, 1, 1, 0, 0, 0 }; 20 for (int i = 0; i < dateStrArray.length; i++) { 21 if (i < 6) { 22 timeArray[i] = Integer.valueOf(dateStrArray[i]); 23 } 24 } 25 newTimeStr = String.format("%s-%s-%s %s:%s:%s", timeArray[0], timeArray[1], timeArray[2], timeArray[3], timeArray[4], timeArray[5]); 26 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 27 Date d = null; 28 try { 29 d = sdf.parse(newTimeStr); 30 } catch (ParseException e) { 31 e.printStackTrace(); 32 } 33 return d; 34 } 35 36 // Date转字符串 37 public static String date2dateStr(Date date) { 38 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date); 39 } 40 41 @InitBinder 42 public void initBinder(WebDataBinder binder) { 43 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { 44 @Override 45 public String getAsText() { 46 return date2dateStr((Date) getValue()); 47 } 48 49 @Override 50 public void setAsText(String text) { 51 setValue(dateStr2date(text)); 52 } 53 }); 54 } 55}
第二种方式:
1.定义自己的WebBindingInitializer
1package com.xxx.blog.util; 2 3import java.util.Date; 4import java.text.SimpleDateFormat; 5 6import org.springframework.beans.propertyeditors.CustomDateEditor; 7import org.springframework.web.bind.WebDataBinder; 8import org.springframework.web.bind.support.WebBindingInitializer; 9import org.springframework.web.context.request.WebRequest; 10 11public class MyWebBindingInitializer implements WebBindingInitializer { 12 13 @Override 14 public void initBinder(WebDataBinder binder, WebRequest request) { 15 // TODO Auto-generated method stub 16 binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false)); 17 } 18 19}
2.在springMVC的配置文件里面定义一个AnnotationMethodHandlerAdapter,并设置其WebBindingInitializer属性为我们自己定义的WebBindingInitializer对象
1<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 2 <property name="cacheSeconds" value="0"/> 3 <property name="webBindingInitializer"> 4 <bean class="com.xxx.blog.util.MyWebBindingInitializer"/> 5 </property> 6</bean>