註冊自定義屬性編輯器一次爲整個應用程序重寫addFormatters WebMvcConfigurerAdapter的方法在你的配置類。
舉例日期(與Java配置)
@EnableWebMvc
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
// ...
@Override
public void addFormatters(final FormatterRegistry registry) {
registry.addFormatterForFieldType(java.sql.Date.class, new DateFormatter());
}
// ...
}
,使你自己的,它實現格式化接口,這樣的事情
public final class DateFormatter implements Formatter<java.sql.Date> {
private String pattern;
public DateFormatter() {
this("yyyy-MM-dd");
}
public DateFormatter(final String pattern) {
this.pattern = pattern;
}
public String print(final java.sql.Date date, final Locale locale) {
if (date == null) {
return "";
}
return getDateFormat(locale).format(date);
}
public java.sql.Date parse(final String formatted, final Locale locale) throws
ParseException {
if (formatted.length() == 0) {
return null;
}
java.util.Date udDate = getDateFormat(locale).parse(formatted);
return new java.sql.Date(udDate.getTime());
}
protected DateFormat getDateFormat(final Locale locale) {
DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale);
dateFormat.setLenient(false);
return dateFormat;
}
}
這是日期格式類它。
問題是重複的http://stackoverflow.com/questions/1268021/how-can-i-register-a-global-custom-editor-in-spring-mvc – C0deAttack 2012-04-02 15:00:02