Java Spring Thymeleaf错误将枚举的集合绑定到复选框

时间:2016-03-09 22:38:30

标签: java spring enums thymeleaf

我正在使用Java8,Spring Boot 1.2.3和Thymeleaf编写应用程序。我想在Accommodation类中使用AccommodationType(enum)的集合并将它们显示为Checkbox,因此用户可以选择住宿中可用的AccommodationType。

不幸的是,当我尝试显示createAccommodation页面时出现错误:

public enum AccommodationType {
    singleRoom,
    doubleRoom,
    moreBeddedRoom,
    apartment;    
}

public class Accommodation {

    @Id
    private String id;

    @NotEmpty
    private String name;

    @NotNull
    private BigDecimal price;

    private List<AccommodationType> types = new ArrayList<AccommodationType>();

    .....

    public List<AccommodationType> getTypes() {
        return new ArrayList<AccommodationType>(types);
    }

    public void setTypes(List<AccommodationType> types) {
        types = new ArrayList<AccommodationType>(types);
    }
}

我的模型,简化:

@Controller
public class AccommodationController {

    private final AccommodationRepository accommodationRepository;

    @Autowired
    public AccommodationController(
            AccommodationRepository anAccommodationRepository) {
        this.accommodationRepository = anAccommodationRepository;
    }

    @ModelAttribute("allTypes")
    public List<AccommodationType> populateAccommodationTypes() {
        return Arrays.asList(AccommodationType.values());
    }

    @RequestMapping(value = "/accommodation/create", method = RequestMethod.GET)
    public ModelAndView showCreateAccommodationPage() {
        return new ModelAndView("createAccommodation", "accommodation",
                new Accommodation());
    }

    @RequestMapping(value = "/accommodation/create", method = RequestMethod.POST)
    public String handleAccommodationCreate(
            @Valid @ModelAttribute("accommodation") Accommodation anAccommodation,
            BindingResult aBindingResult) {
        if (aBindingResult.hasErrors()) {
            return "createAccommodation";
        }
        accommodationRepository.save(anAccommodation);
        return "redirect:/accommodation";
    }
}

控制器:

<form class="form-horizontal" role="accommodation" th:action="@{/accommodation/create}" method="post">
....
<div class="form-group">
    <ul>
      <li th:each="type : ${allTypes}">
        <input type="checkbox" th:field="*{types}" th:value="${type}" />
        <label th:for="${#ids.prev('types')}" th:text="#{${type}}"></label>
      </li>
    </ul>
</div>
....

视图模板:

{{1}}

有人知道我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

问题是表格标签中缺少th:object:

<form class="form-horizontal" th:object="${accommodation}"
                        th:action="@{/accommodation/create}" method="post">