选择带有对象的标签-Thymeleaf和Spring MVC


问题内容

我试图更改此示例thymeleafexamples-
stsm
的代码,所以我将类类型的枚举类型更改为:

Type.java

public class Type {

    private Integer id; 
    private String type; 
   ...getters and setters 
}

SeedStarterMngController.java

@ModelAttribute("allTypes") 
    public List<Type> populateTypes() { 
        Type type1 = new Type(); 
        type1.setId(1); 
        type1.setType("OUTDOOR");

        Type type2 = new Type(); 
        type2.setId(2); 
        type2.setType("INDOOR");

        List<Type> tipos = new ArrayList<Type>(); 
        tipos.add(type1); 
        tipos.add(type2); 
        return tipos; 
    }

seedstartermng.html

<select th:field="*{type}">
    <option th:each="type : ${allTypes}" th:value="${type}" th:text="${type.type}">Wireframe</option>
</select>

因此,我无法添加Seed Starter。

我的输出html是

<select id="type" name="type">
    <option value="thymeleafexamples.stsm.business.entities.Type@2c08cec0">OUTDOOR</option>
    <option value="thymeleafexamples.stsm.business.entities.Type@26cf024">INDOOR</option>
</select>

错误是

无法将类型java.lang.String的属性值转换为属性类型的必需类型thymeleafexamples.stsm.business.entities.Type;嵌套异常为java.lang.IllegalStateException:无法将[java.lang.String]类型的值转换为属性类型的必需类型[thymeleafexamples.stsm.business.entities.Type]:没有找到匹配的编辑器或转换策略

我该怎么做才能正确映射类型?我希望你能帮助我。谢谢。


问题答案:

该错误消息基本上表明Spring不知道如何将字符串thymeleafexamples.stsm.business.entities.Type@2c08cec0转换为Type的实例。这是您代码中的错误,因为尝试这样做没有任何意义。

您不应该将toString()Object 的值用作表单下拉标识符。您需要一个(更好)的代码策略来识别用户选择的类型。

常用方法是使用id属性:

<option th:each="type : ${allTypes}" th:value="${type.id}" th:text="${type.type}">Wireframe</option>

提交表单后,您需要根据其控制器上的ID名称撤消Type的实例