码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC自定义属性编辑器

时间:2015-05-13 10:16:00      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:spring mvc

在SpringMVC3.0.5中验证通过。

Spring MVC有一套常用的属性编辑器,这包括基本数据类型及其包裹类的属性编辑器,String属性编辑器,JavaBean的属性编辑器等。但我们还需要自己注册一些自定义的属性编辑器,如特定时间格式的属性编辑器就是一个典型的例子。

Spring MVC允许向整个Spring框架注册属性编辑器,对所有的Controller都起作用。(通过AnnotationMethodHandlerAdapter配置)

SpringMVC也可以只针对某个Controller注册单独的属性编辑器,此时该属性编辑器只作用在当前Controller。(通过@InitBinder注解)

1、  向整个Spring MVC框架注册自定义编辑器:在Dispatcher-servlet.xml文件中配置如下:

<!-- 启动基于注解的SpringMVC.注意:当使用了<mvc:annotation-driven />的时候,它 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean。这时候就无法指定的全局属性编辑器了,解决办法就是手动的添加上述bean。-->
            <!-- <mvc:annotation-driven/> -->
            <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
             <property name="webBindingInitializer">
                 <bean class="com.springmvc.demo.util.DateBindingEditor"/>
                         </property>
            </bean>
            
package com.springmvc.demo.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 DateBindingEditor implements WebBindingInitializer {
 
            @Override
            public void initBinder(WebDataBinder binder, WebRequest arg1) {
                        // TODO Auto-generated method stub
                        System.out.println(this.getClass()+"---initBinder---");
                        binder.registerCustomEditor(Date.class, 
                                                 new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
            }
            
}

 

2、  在Controller中定义单独的属性编辑器

@Controller

@RequestMapping(value="/test1")

@SessionAttributes("curruser")

public class MyController {

    ......

    @InitBinder

    public void initBinder(ServletRequestDataBinder binder){

             binder.registerCustomEditor(Date.class,

                                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));

}

......

}

 

SpringMVC自定义属性编辑器

标签:spring mvc

原文地址:http://blog.csdn.net/zxygww/article/details/45689085

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!