前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring注入 属性编辑器

spring注入 属性编辑器

作者头像
码客说
发布2019-10-22 14:02:18
3650
发布2019-10-22 14:02:18
举报
文章被收录于专栏:码客码客码客

作用

表单提交过来的所有字段都是字符串类型的,之所以vo对象中的Integer等类型能被注入是因为springmvc已经默认定义了许多属性编辑器来进行处理,但是你传过来一个2014-01-01 16:10 他就不会处理了 所以写一个自定义编辑器就能解决了

使用方式

添加自定义属性编辑器

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
        @Override
        public String getAsText() {
            return ZJ_DateUtils.date2datetimeStr((Date) getValue());
        }
        @Override
        public void setAsText(String text) {
            setValue(ZJ_DateUtils.str2date(text));
        }
    });
}

时间转换工具类

public class ZJ_DateUtils {
    private static String DateTime_Format_Str = "yyyy-MM-dd HH:mm:ss";
    private static String Time_Format_Str = "HH:mm:ss";
    private static String Hour_Minute_Format_Str = "HH:mm";
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 日期字符串转Date
    public static Date str2date(String dateStr) {
        if (null == dateStr || "".equals(dateStr)) {
            return null;
        }
        dateStr = dateStr.replaceAll("-", " ").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(DateTime_Format_Str);
        Date d = null;
        try {
            d = sdf.parse(newTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }
    // Date转字符串
    public static String date2datetimeStr(Date date) {
        return new SimpleDateFormat(DateTime_Format_Str).format(date);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-05-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 作用
  • 使用方式
    • 添加自定义属性编辑器
      • 时间转换工具类
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档