百里香的输入日期错误

时间:2016-02-24 14:24:26

标签: spring thymeleaf

我有一个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:/";
}

1 个答案:

答案 0 :(得分:0)

春天不懂生日&#34;生日&#34; java.lang.String中的字段,因为在你的Bean中它是一个java.util.Calendar。 您需要配置转换器。这样的事情:

@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();
    }
}