SpringMVC 日期/时间 参数解析

0
(0)

Spring mvc 默认设置对日期和时间参数转换不是很理想,自带的CustomDateEditor 只能传入一个DateFormat,而我们知道SimpleDateFormat 又是线程不安全的,我们可以通过自定义一个PropertyEditorSupport的子类,用其他方式来实现日期格式的转换。少比比,直接上代码:

/*
 * Copyright (c) 2017 西安才多信息技术有限责任公司。
 * 项目名称:dev
 * 文件名称:DateEditor.java
 * 日期:17-6-4 下午2:06
 * 作者:yangyan
 *
 */

package cn.firegod.common.binder;

import cn.firegod.common.utils.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

/**
 * Created by yangyan on 2017/6/4.
 */
public class DateEditor extends PropertyEditorSupport {

    private String pattern[] = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
            , "yyyy/MM/dd"};


    /**
     * Parse the Date from the given text, using the lang3 DateUtils.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || !StringUtils.hasText(text)) {
            // Treat empty String as null value.
            setValue(null);
        } else {
            try {
                setValue(DateUtils.parseDate(text, pattern));
            } catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }

    /**
     * Format the Date as String, using the lang3 Utils.
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        if (value instanceof java.sql.Date) {
            return (value != null ? DateFormatUtils.ISO_DATE_FORMAT.format(value) : "");
        } else if (value instanceof java.sql.Timestamp) {
            return (value != null ? DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss") : "");
        } else {
            return (value != null ? DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss") : "");
        }
    }
}

然后在我们的 Controller 里面加入下面的代码注册一下,我这里设置在了所有 Controller 的父类上:

@InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class, new DateEditor());
    }

 

这篇文章有用吗?

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据