springMVC自定义属性编辑器

来源:互联网 发布:中山大学网络不好 编辑:程序博客网 时间:2024/05/22 11:30

自定义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 {// 日期字符串转Datepublic 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);}@InitBinderpublic void initBinder(WebDataBinder binder) {binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {@Overridepublic String getAsText() {return date2dateStr((Date) getValue());}@Overridepublic 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 {@Overridepublic void initBinder(WebDataBinder binder, WebRequest request) {// TODO Auto-generated method stubbinder.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>


0 0
原创粉丝点击