Невозможно привязать список объектов из Thymeleaf к Spring Controller - PullRequest
2 голосов
/ 01 мая 2020

Я новичок в загрузке Spring и пытаюсь реализовать пример книги "Spring In Action" через Thymeleaf, но я получаю ошибки typeMismatch, когда контроллер проверяет объект в почтовом запросе.

org.springframework.validation .BeanPropertyBindingResult: 1 сообщение об ошибке по умолчанию [Не удалось преобразовать значение свойства типа 'java .lang.String []' в требуемый тип 'java .util.List' для свойства 'ингридиенты'; Вложенное исключение: java .lang.IllegalStateException: Невозможно преобразовать значение типа 'java .lang.String' в требуемый тип 'com.practice.spring.model.Ingredient' для ингредиентов свойства '[0]': нет соответствия найдены редакторы или стратегия конвертации]

  • Запрос на получение отображает все ингредиенты, основанные на ТИПЕ.
  • Запрос на отправку собирает данные, относящиеся к Taco, и СОХРАНЯЕТ их соответственно. Во время проверки Taco Object появляется ошибка.

Как преобразовать список строк в список ингредиентов в шаблоне Thymeleaf.

POJO объекты


public class Ingredient {

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    private String id;
    private String name;
    private Type type;

    public Ingredient(String id, String name, Type type) {
        this.id = id;
        this.name = name;
        this.type = type;
    }

    public enum Type {
        WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE;
    }

}
public class Taco {

    @NotNull
    @Size(min = 5, message = "Please enter at least 5 characters")
    private String name;

    @Size(min = 1, message = "Atleast 1 Ingredient should be selected")
    private List<Ingredient> ingredients;

    private Long id;

    private Date createdDt;

    public List<Ingredient> getIngredients() {
        return ingredients;
    }

    public void setIngredients(List<Ingredient> ingredients) {
        this.ingredients = ingredients;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getCreatedDt() {
        return createdDt;
    }

    public void setCreatedDt(Date createdDt) {
        this.createdDt = createdDt;
    }

}

Контроллер


@Controller
@RequestMapping("/design")
public class DesignTacoController {

    @Autowired
    private IngredientRepository ingredientRepository;

    @Autowired
    private TacoRepository tacoRepository;


    @ModelAttribute(value = "design")
    public Taco createTaco() {
        return new Taco();
    }

    @GetMapping
    public String showDesign(Model model) {

        List<Ingredient> ingredients = new ArrayList<>();
        ingredientRepository.findAll().forEach(ingred -> ingredients.add(ingred));

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

        return "design";

    }

    @PostMapping
    public String processDesign(@Valid @ModelAttribute("design") Taco design, Errors errors) {
        if (errors.hasErrors()) {
            return "design";
        }
        tacoRepository.save(design);

        return "redirect:/order/current";
    }

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

}

Шаблон Thymeleaf


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
</head>
<body>
    <h1>Design your taco!</h1>
    <form method="POST" th:object="${design}">
        <div class="grid">
            <div class="ingredient-group" id="wraps">
                <h3>Designate your wrap:</h3>
                <div th:each="ingredient : ${wrap}">
                    <input name="ingredients" type="checkbox" 
                        th:value="${ingredient.id}" /> <span th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="proteins">
                <h3>Pick your protein:</h3>
                <div th:each="ingredient : ${protein}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="cheeses">
                <h3>Choose your cheese:</h3>
                <div th:each="ingredient : ${cheese}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="veggies">
                <h3>Determine your veggies:</h3>
                <div th:each="ingredient : ${veggies}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="sauces">
                <h3>Select your sauce:</h3>
                <div th:each="ingredient : ${sauce}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
        </div>
        <div>
            <h3>Name your taco creation:</h3>
            <input type="text" th:field="*{name}" /> <br />
            <button>Submit your taco</button>
        </div>
    </form>
</body>
</html>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...