SpringMVC 日期/时间 参数解析
2023-04-18 14:30:15 时间
发表于2017-06-042019-01-01 作者 wind
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());
}
相关文章
- 【技术种草】cdn+轻量服务器+hugo=让博客“云原生”一下
- CLB运维&运营最佳实践 ---访问日志大洞察
- vnc方式登陆服务器
- 轻松学排序算法:眼睛直观感受几种常用排序算法
- 十二个经典的大数据项目
- 为什么使用 CDN 内容分发网络?
- 大数据——大数据默认端口号列表
- Weld 1.1.5.Final,JSR-299 的框架
- JavaFX 2012:彻底开源
- 提升as3程序性能的十大要点
- 通过凸面几何学进行独立于边际的在线多类学习
- 利用行动影响的规律性和部分已知的模型进行离线强化学习
- ModelLight:基于模型的交通信号控制的元强化学习
- 浅谈Visual Source Safe项目分支
- 基于先验知识的递归卡尔曼滤波的代理人联合状态和输入估计
- 结合网络结构和非线性恢复来提高声誉评估的性能
- 最佳实践丨云开发CloudBase多环境管理实践
- TimeVAE:用于生成多变量时间序列的变异自动编码器
- 具有线性阈值激活的神经网络:结构和算法
- 内网渗透之横向移动 -- 从域外向域内进行密码喷洒攻击