SpringMVC自定义属性编辑器

来源:互联网 发布:淘宝卡密自动发货软件 编辑:程序博客网 时间:2024/06/07 18:45

在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));

}

......

}

 

0 0
原创粉丝点击