Spring MVC:允许的默认日期格式是什么?
在我的Spring Web MVC应用程序中,我在@Controller
有一堆方法,它们使用@RequestParam
接受Date
作为输入参数。 没有定义任何自定义数据绑定器或属性编辑器(我承认我仍然不清楚这两者之间的区别),默认支持哪些日期格式? 例如,我注意到像’11 / 12/2012 16:50 PM’之类的工作正常,但像’1352815200000’这样的普通milis值被拒绝了。
编辑:我得到的具体exception是:“无法将类型’java.lang.String’的值转换为必需的类型’java.util.Date’;嵌套exception是java.lang.IllegalStateException:无法转换类型的值[java .lang.String]到必需的类型[java.util.Date]:找不到匹配的编辑器或转换策略“
我相信如果没有指定转换器,Spring转换系统将最终调用不推荐使用的Date
构造函数,它将String作为参数。
/** * Allocates a
Date
object and initializes it so that * it represents the date and time indicated by the string *s
, which is interpreted as if by the * {@link Date#parse} method. * * @param sa string representation of the date. * @see java.text.DateFormat * @see java.util.Date#parse(java.lang.String) * @deprecated As of JDK version 1.1, * replaced byDateFormat.parse(String s)
. */ @Deprecated public Date(String s) { this(parse(s)); }
通常应用程序有不同的要求 – 一些与本地时间一起工作(也可能是浏览器特定的事情和用户时区设置),有些不需要存储日期 – 因此最好实施日期转换策略在客户端和服务器端。
PS请注意, Date.parse()
也已弃用。
允许的日期格式可能取决于您当前的Locale。
您可以添加一个处理程序,用于转换您喜欢的格式的日期。
我不确定是哪一个。 @InitBinder显示了从任何格式转换日期的示例..
希望这对你有用。
创建一个类注册日期格式的编辑器。
import org.springframework.beans.PropertyEditorRegistrar import org.springframework.beans.PropertyEditorRegistry import org.springframework.beans.propertyeditors.CustomDateEditor import java.text.SimpleDateFormat public class CustomDateEditorRegistrar implements PropertyEditorRegistrar { public void registerCustomEditors(PropertyEditorRegistry registry) { String dateFormat = 'yyyy/MM/dd' registry.registerCustomEditor(Date, new CustomDateEditor(new SimpleDateFormat(dateFormat), true)) } }