我正在寻找当前问题的解决方案。我有一个由 Hibernate 映射的经典 POJO Date
多变的。
@Entity
@Table(name="record")
public class Record implements Serializable {
@Column(name = Record.COLUMN_CREATED)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
@DateTimeFormat(pattern="dd.MM.yyyy hh:mm")
private Date created;
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
该实体保存在 MySQL 数据库的 TIMESTAMP 变量中 (2013-09-25 22:13:18.000)。
我正在使用 Spring 表单来显示 POJO 中保存的数据。
<form:form method="post" commandName="record" action="record/update.htm">
<table>
<tr>
<td><form:label path="<%=Record.COLUMN_CREATED%>"><spring:message code="administration.record.created"/>:</form:label></td>
<td><form:input path="<%=Record.COLUMN_CREATED%>"/></td>
</tr>
</table>
</form:form>
我的问题是,当我想编辑这个 POJO 并将其发送到 spring 表单中显示时,我得到的日期为 2013-09-25 22:13:18.000,与 MySQL 时间戳的格式完全相同。但我想根据我使用 @DateTimeFormat 注释设置的模式来格式化此日期。
有人可以告诉我,我做错了什么吗?非常感谢,Ondrej。
编辑:我有@InitBinder
已经,但它仅在我通过表单创建新对象时才有效,因此它会转换 String
至Date
。但是当我想用数据库中的现有数据填充表单输入时,它不起作用。
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy h:mm");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
我使用的是Spring 3.1.1.RELEASE,没有Joda时间,只是普通的java.util.Date。
<mvc:annotation-driven/>
在dispatcher-servlet.xml中设置正确。当我使用调试器时,我可以看到,在从表单输入值创建新对象时,方法 setAsText(String text)
的CustomDateEditor
用来。我期望第二种方法,String getAsText()
将用于在填写表单输入时将数据格式化为字符串。但是,事实并非如此!
最佳答案
@DateTimeFormat(pattern="dd.MM.yyyy hh:mm")
注释基本上是说当你得到 String
时在特定模式中,将其转换为
java.util.Date
,java.util.Calendar
,java.long.Long
, or Joda Time fields.
就您而言,它是 java.util.Date
.
当你做类似的事情时
<spring:message code="administration.record.created"/>:</form:label>
您刚刚调用toString()
关于created
Date
目的。 Date
返回 toString()
中的字符串时,类在内部使用自己的格式这就是你所看到的。
考虑使用 fmt:formatDate
来自 JSTL 的标签。
关于java - 如何使用@DateTimeFormat在Spring表单中绑定(bind)日期字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19015581/