0

Начал изучать Spring и столкнулся с такой ошибкой: org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/home.html]"). IDEA ругается на ingredients в <input th:field="*{ingredients}" type="checkbox" и name в

<!DOCTYPE html> <html lang="en"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"> <head>
    <meta charset="UTF-8">
    <title>Taco Cloud</title>
    <link rel="stylesheet" th:href="@{/styles.css}" /> </head>
    <body>
        <h1>Design your Taco!</h1>
        <img th:src="@{/images/taco.png}"/>

        <form method="POST" th:object="${taco}">
            <div class="grid">
                <div class="ingredient-group" id="wraps">
                    <h3>Designate your wrap:</h3>
                    <div th:each="ingredient : ${wrap}">
                        <input th:field="*{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 th:field="*{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 th:field="*{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 th:field="*{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 th:field="*{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>

Старый вариант Контроллера:

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import tacos.Ingredient;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import tacos.Ingredient;
import tacos.Ingredient.Type;
import tacos.Taco;
import tacos.TacoOrder;

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

    @ModelAttribute
    public void addIngredientsToModel(Model model) {
        List<Ingredient> ingredients = Arrays.asList(
                new Ingredient("FLTO", "Flour Tortilla", Ingredient.Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Ingredient.Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Ingredient.Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Ingredient.Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomates", Ingredient.Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Ingredient.Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Ingredient.Type.CHEESE),
                new Ingredient("JACK", "Monterrey Jack", Ingredient.Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Ingredient.Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Ingredient.Type.SAUCE)
        );

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

    @ModelAttribute(name = "tacoOrder")
    public TacoOrder order() {
        return new TacoOrder();
    }
    @ModelAttribute(name = "taco")
    public Taco taco() {
        return new Taco();
    }
    @GetMapping
    public String showDesignForm() {
        return "design";
    }

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

Новый вариант контроллера:

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import tacos.tacostacos.Ingredient.Type;

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

    @GetMapping
    public String showDesignForm(Model model) {
        List<Ingredient> ingredients = Arrays.asList(
                new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomatos", Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Type.VEGGIES),
                new Ingredient("CHED", "Chedder", Type.CHEESE),
                new Ingredient("JACK", "Monterry Jack", Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Type.SAUCE));

        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(),
                    filterByType(ingredients, type));
        }
        return "design";
    }
    @ModelAttribute(name = "tacoOrder")
    public TacoOrder order() {
        return new TacoOrder();
    }

    @ModelAttribute(name = "taco")
    public Taco taco() {
        return new Taco();
    }

    private Iterable<Ingredient> filterByType(List<Ingredient> ingredients, Type type) {
        return ingredients.stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}
6
  • Приложите Ваш контроллер полностью, которые заполняет данные для этого представления
    – ulxanxv
    3 июн 2022 в 7:29
  • Добавил контроллер 3 июн 2022 в 12:01
  • Вы должны класс Model заполнять в методе showDesignForm()
    – ulxanxv
    4 июн 2022 в 5:33
  • Аннотация @ModelAttribute нужна ДЛЯ ПРИНЯТИЯ МОДЕЛИ СО СТРАНИЦЫ, а не для отправки туда. Для отправки её нужно заполнять непосредственно в методе, который возвращает View. Переделайте метод в public String showDesignForm(Model model) и заполняйте
    – ulxanxv
    4 июн 2022 в 5:35
  • Правильно ли я Вас понял и изменил метод? 4 июн 2022 в 13:49

1 ответ 1

0

Аннотация @ModelAttribute нужна ДЛЯ ПРИНЯТИЯ МОДЕЛИ СО СТРАНИЦЫ, а не для отправки туда. Для отправки её нужно заполнять непосредственно в методе, который возвращает View. Переделайте метод в public String showDesignForm(Model model) и заполняйте.

Пример метода :

@GetMapping
public String showDesignForm(Model model) {
    List<Ingredient> ingredients = Arrays.asList(
            new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),
            new Ingredient("COTO", "Corn Tortilla", Type.WRAP),
            new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
            new Ingredient("CARN", "Carnitas", Type.PROTEIN),
            new Ingredient("TMTO", "Diced Tomatos", Type.VEGGIES),
            new Ingredient("LETC", "Lettuce", Type.VEGGIES),
            new Ingredient("CHED", "Chedder", Type.CHEESE),
            new Ingredient("JACK", "Monterry Jack", Type.CHEESE),
            new Ingredient("SLSA", "Salsa", Type.SAUCE),
            new Ingredient("SRCR", "Sour Cream", Type.SAUCE));

    model.addAttribute("ingredients", ingredients);
    return "design";
}

На данный момент на странице вы обращаетесь к переменной ingredients, которой не существует :)

model.addAttribute(key, value): key - это ключ, по которому можно обращаться к переменной на странице; value - значение ключа. Почитайте внимательно свой код и Вы увидите, что вместо добавления ключа ingredients, вы добавляете ваши списки по ключам type.toString().toLowerCase(). Соответственно никакой переменной ingredients на странице НЕТ. Есть wrap, protein, veggies, cheese, sauce

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.