SpringMVC自定义属性编辑器

在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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值