0

I'd like Play!Framework to convert a Timestamp sent via POST into a java.util.Date format in the Model, but I don't know if it's directly possible.

Here's my model :

public class Contact extends Model {
    @Id
    private Long id;

    @Constraints.Required
    private String name;

    @JsonIgnore
    @Temporal(TemporalType.TIMESTAMP)
    private Date removed = null; // When the contact is no longer active
}

I tried to add @Formats.DateTime(pattern="?") to removed, but since DateTime use SimpleDateFormat, I wasn't able to found which pattern to use to convert a timestamp to the correct Date.

How can I do ?

4

1 回答 1

1

好的,我会回答自己,这就是我所做的(也许不是最好的方法,但它有效)。

我不使用模型将发布的参数与删除的值匹配,而是在我的 Controller 中执行此操作:

String[] accepts = {"name", "datestamp"};
Form<Contact> form = Form.form(Contact.class).bindFromRequest(accepts);

Date date = null;
try {
    date = new Date(Long.parseLong(form.field("datestamp").value()));
}
catch (NumberFormatException nfe) {}

if (date == null) {
    form.reject("date", "error.invalid");
}

if (form.hasErrors()) {
    return badRequest(form.errorsAsJson());
}
else {
    Contact contact = form.get();
    contact.setRemoved(date);

    contact.save();
    return ok();
}
于 2013-06-03T12:03:38.467 回答