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()); }
了解 工作生活心情记忆 的更多信息
订阅后即可通过电子邮件收到最新文章。