我有一个HTML代码:
<input type="date" th:field="*{birthday}"/>
当我提交表单时,我收到错误:
Failed to convert property value of type [java.lang.String] to required type [java.util.Calendar] for property birthday; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Calendar] for property birthday: no matching editors or conversion strategy found
我使用Spring。我该如何解决?
感谢。
控制器:
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String updateMember(Model model,
@Valid Member member,
BindingResult bindingResult,
@RequestParam(value="action", required=true) String action) {
System.out.println("updateMember POST - start");
System.out.println(member);
if (bindingResult.hasErrors()) {
System.out.println("bindingResult.hasErrors");
return "member_edit";
}
memberService.update(member);
// todo verificar se precisa dessa linha mesmo chamando o redirect
model.addAttribute("members", memberService.getAll());
return "redirect:/";
}
答案 0 :(得分:0)
@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter {
@Bean
public CalendarFormatter calendarFormatter() {
return new CalendarFormatter();
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(calendarFormatter());
}
}
你的CalendarFormatter看起来像这样:
public class CalendarFormatter implements Formatter<Calendar> {
final String defaultDateFormat = "dd.MM.yyyy";
@Override
public String print(Calendar object, Locale locale) {
return new SimpleDateFormat(defaultDateFormat).format(object.getTime());
}
@Override
public Calendar parse(String text, Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(defaultDateFormat);
Date date = sdf.parse(text);
return sdf.getCalendar();
}
}