• 表单中的日期 字符串和Javabean中的日期类型的属性自动转换


    搞了一上午的bug最终还是因为自己springMVC的注解不熟悉的原因,特记录。

    在实际操作中经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换, 而springMVC默认不支持这个格式的转换,所以必须要手动配置, 自定义数据类型的绑定才能实现这个功能。

    比较简单的可以直接应用springMVC的注解@initbinder和spring自带的WebDataBinder类和操作

    有些类型的数据是无法自动转换的,比如请求参数中包含时间类型的数据,无法自动映射到Controller里的Date参数。需要使用@initBinder注解为binder提供一个数据的转换器,这个转换器可以自己实现,也可以用spring官方的一些实现。比如:

    复制代码
    package com.wang.action;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    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;
    import org.springframework.web.bind.annotation.RequestParam;
    /**
     * 测试@initBinder注解
     * @author wlyfree
     */
    @Controller
    public class BinderAction {
    
        @RequestMapping("/sb2.do")
        public void doTest(@RequestParam(value="name")String name,@RequestParam(value="age")double age,@RequestParam(value="nowTime")Date nowTime){
            System.err.println("name:" + name);
            System.err.println("age:" + age);
            System.err.println("nowTime:" + nowTime);
        } 
        
        @InitBinder
        public void initBinder(WebDataBinder binder){
            binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        }
    }
    复制代码
  • 相关阅读:
    Geohash
    Go加密解密之RSA[转]
    在MACOS上实现交叉编译
    [转]MySQL与MongoDB的操作对比
    CentOS 6 使用 yum 安装MongoDB及服务器端配置
    Ubuntu下PHP的扩展
    golang 图片处理,剪切,base64数据转换,文件存储
    性能测试应用领域
    性能测试用例、策略和方法
    性能测试类型
  • 原文地址:https://www.cnblogs.com/panxuejun/p/7280035.html
Copyright © 2020-2023  润新知