簡體   English   中英

Spring無法識別DateTime字段的格式

[英]Format of DateTime field not recognized by Spring

我正在使用Spring 3.2.4開發Web應用程序。 我有一些表格,其中包含日期和時間。 我的一塊jsp:

<form:form method="post" action="/add" modelAttribute="licence">
    ...
    <form:input type="datetime" path="beginDate"/>
    <form:input type="datetime" path="endDate"/>
    <form:input path="quantityLimit"/>
    ...
</form:form>

正常形式,沒什么特別的。 我正在使用datepicker,它以格式yyyy-MM-dd HH:mm給出了日期,所以我已經將它添加到我的控制器:

@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    dateFormat.setLenient(true);
    webDataBinder.registerCustomEditor(DateTime.class, new CustomDateEditor(dateFormat, true));
}

另外,我已經將<mvc:annotation-driven/>到我的servlet配置xml中,如某些博客中所述。

有目標控制器:

@RequestMapping(value = "/{softwareId}/licence/add", method = RequestMethod.POST)
public String addLicence(@PathVariable("softwareId") Long softwareId, Licence licence, Model model) {
    Software software = softwareRepository.findOne(softwareId);
    licence.setSoftware(software);
    licenceRepository.save(licence);
    return ADMIN_PATH + "softwareEdit";
}

軟件類看起來像這樣:

@Entity
@Table(name = "licences")
public class Licence {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "begin_date")
private DateTime beginDate;

@Column(name = "end_date")
private DateTime endDate;

@Column(name = "quantity_limit")
private Long quantityLimit;

@ManyToOne
private Software software;

//getters, setters, etc.
}

問題是:當我提交我的表單時,dateTime字段為空它可以很好地工作,但是當我在日期字段中有任何內容時(無論它是否格式正確)我得到HTTP Error 400: Bad Request 在控制台中沒有異常,只有錯誤的請求,但我很確定它與日期解析有關。

是否有一個很好的描述方法來處理Spring應用程序中的表單中的日期和時間字段?

讓您的生活變得簡單並使用@DateTimeFormat ,擺脫您的WebDataBinder配置。 似乎CustomDateEditor只適用於java.util.Date而Spring沒有其他(默認/未指定)機制將String轉換為DateTime

@DateTimeFormat就是這樣一種機制。

@Column(name = "begin_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private DateTime beginDate;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM