thymeleaf 无法将 java.lang.String 类型的属性值转换为所需类型 java.util.List

2023-12-08

我是 Spring 和 Spring Boot 的新手,正在阅读一本充满缺失信息的书。

我有一堂炸玉米饼课:

public class Taco {

    ...

    @Size(min=1, message="You must choose at least 1 ingredient")
    private List<Ingredient> ingredients;

    ...
}

如你看到的ingredients属于类型List<Ingredient>这就是问题所在,它曾经是这样的类型List<String>但那是在我开始将数据保存到数据库之前,现在它必须是List<Ingredient>这打破了整个事情。

在控制器中,我有以下内容(除其他外,我认为这是解决当前问题唯一所需的代码,但如果您需要更多代码,请告诉我):

@ModelAttribute
    public void addIngredientsToModel(Model model) {
        List<Ingredient> ingredients = new ArrayList<>();
        ingredientRepo.findAll().forEach(i -> ingredients.add(i));

        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
        }
    }

private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type) {
        return ingredients
                    .stream()
                    .filter(x -> x.getType()
                    .equals(type))
                    .collect(Collectors.toList());
    }

最后在我的百里香文件中我有:

<span class="text-danger" 
                th:if="${#fields.hasErrors('ingredients')}" 
                th:errors="*{ingredients}">
            </span>

这会导致错误:

thymeleaf Failed to convert property value of type java.lang.String to required type java.util.List

再次,当private List<Ingredient> ingredients; was private List<String> ingredients;它有效,但现在必须是private List<Ingredient> ingredients;由于它保存在数据库中的方式,但此时它损坏了,如何修复它?


我也遇到了同样的问题,我们需要一个转换器。

package tacos.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import tacos.Ingredient;
import tacos.data.IngredientRepository;

@Component
public class IngredientByIdConverter implements Converter<String, Ingredient> {

private IngredientRepository ingredientRepo;

@Autowired
public IngredientByIdConverter(IngredientRepository ingredientRepo) {
    this.ingredientRepo = ingredientRepo;
}

@Override
public Ingredient convert(String id) {
    return ingredientRepo.findOne(id);
}

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

thymeleaf 无法将 java.lang.String 类型的属性值转换为所需类型 java.util.List 的相关文章

随机推荐