如何使用Spring MVC在文本字段中設置日期的格式?使用Spring MVC爲輸入文本設置日期格式
我使用Spring Form標籤庫和input
標籤。
我現在得到的是這樣的Mon May 28 11:09:28 CEST 2012
。
我想以dd/MM/yyyy
格式顯示日期。
如何使用Spring MVC在文本字段中設置日期的格式?使用Spring MVC爲輸入文本設置日期格式
我使用Spring Form標籤庫和input
標籤。
我現在得到的是這樣的Mon May 28 11:09:28 CEST 2012
。
我想以dd/MM/yyyy
格式顯示日期。
登記歲控制器的日期編輯:
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDate.class, new LocalDateEditor());
}
,然後將數據編輯器本身可以是這樣的:
public class LocalDateEditor extends PropertyEditorSupport{
@Override
public void setAsText(String text) throws IllegalArgumentException{
setValue(Joda.getLocalDateFromddMMMyyyy(text));
}
@Override
public String getAsText() throws IllegalArgumentException {
return Joda.getStringFromLocalDate((LocalDate) getValue());
}
}
我用我自己的抽象工具類(喬達)解析日期,其實LocalDates從Joda Datetime library - 建議作爲標準的java日期/日曆是一種可憎的,恕我直言。但你應該明白這個主意。此外,你可以註冊一個全局編輯器,所以你不必每個控制器都做(我不記得是如何的)。
完成!我只是說這個方法我的控制器類:
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
如果您希望將所有日期格式,而無需重複相同的代碼在每一個控制器,可以與@ControllerAdvice註釋的類創建全球InitBinder註解。
創建DateEditor類,將格式化您的日期,就像這樣:
public class DateEditor extends PropertyEditorSupport {
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value));
} catch(ParseException e) {
setValue(null);
}
}
public String getAsText() {
String s = "";
if (getValue() != null) {
s = new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
}
return s;
}
2.創建@ControllerAdvice註釋的類(我把它叫做GlobalBindingInitializer) :
@ControllerAdvice
public class GlobalBindingInitializer {
/* Initialize a global InitBinder for dates instead of cloning its code in every Controller */
@InitBinder
public void binder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateEditor());
}
}
3.在您的Spring MVC配置文件(例如webmvc-config.xml)中添加允許Spring掃描您在其中創建GlobalBindingInitializer類的包的行。例如,如果您在org.example.common包中創建了GlobalBindingInitializer:
<context:component-scan base-package="org.example.common" />
完成!
來源:
謝謝!這絕對比我的解決方案更好。 – davioooh
@davioooh Spring 3.0 +?這是我認爲相關章節http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html「使用propertyregistars」顯示如何在全球範圍內執行 – NimChimpsky
是的,我使用Spring 3.1,但我還是對它不熟悉...(以及對Spring Framework的總體...) – davioooh