Jeśli chcesz sformatować wszystkie dat bez konieczności powtarzania tego samego kodu w każdym kontrolerze, można utworzyć globalnego InitBinder w klasie, z dopiskiem @ControllerAdvice adnotacja.
Kroki
1. Utwórz klasę DateEditor że sformatuje dat, tak:
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. Utwórz klasę uwagami z @ControllerAdvice (nazwałem go 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. W pliku konfiguracyjnym Spring MVC (na przykład webmvc-config.xml) dodaj linie, które umożliwiają Springowi zeskanowanie pakietu, w którym utworzyłeś swoją klasę GlobalBindingInitializer. Na przykład, jeżeli utworzono GlobalBindingInitializer w pakiecie org.example.common:
<context:component-scan base-package="org.example.common" />
Zakończone!
Źródła:
Dziękujemy! to zdecydowanie lepsze niż moje rozwiązanie. – davioooh
@ Daavioooh Spring 3.0 +?Oto odpowiedni rozdział: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html "using propertyregistars" pokazuje, jak to zrobić globalnie – NimChimpsky
Tak, używam Springa 3.1, ale wciąż jestem dla niego nowy ... (i do Spring Framework w ogóle ...) – davioooh