弹簧。 ModelAttribute。 GetMapping。百里香

时间:2019-02-19 08:38:53

标签: java spring spring-mvc thymeleaf

程序无法解析我从控制器以html格式提供的对象。

模型

public class Taco {

    private String name;
    private List<String> ingredients;
}

成分

public class Ingredient {

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



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

}

在控制器中。我用不同的方法尝试了ModelAttribute的不同变体,并跟随了许多示例。但是HTML仍然无法解析。

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



public void addIngredientsToModel(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 Tomatoes", Type.VEGGIES),
            new Ingredient("LETC", "Lettuce", Type.VEGGIES),
            new Ingredient("CHED", "Cheddar", Type.CHEESE),
            new Ingredient("JACK", "Monterrey 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));
    }
}


@GetMapping
@ModelAttribute("design")
public String showDesignForm(Model model) {
    addIngredientsToModel(model);
    model.addAttribute("design", new Taco());
    return "design";
}


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

现在是design.html的一部分。无法解析蛋白质,fasticate.id,fatent.name。我怎样才能解决这个问题?我尝试了不同的方法:

<form method="POST" th:object="${design}">
   <div>
        <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>

3 个答案:

答案 0 :(得分:0)

它引发任何异常吗?现在在我看来,您拥有@GetMapping并尝试过帐表单。尝试将@GetMapping更改为@PostMapping。

答案 1 :(得分:0)

您必须为Taco和成分添加吸气剂和吸气剂。 如果使用Lombok,则可以添加类级别注释@Data。龙目岛将自动生成它。

@Data
public class Taco {

private String name;
private List<String> ingredients;
}

答案 2 :(得分:0)

我没有看到为Ingredients或Taco类定义的构造函数。 如果您没有在问题中包含该内容,而在POST呼叫中遇到错误,请尝试将@RequestMapping(value = "/design")替换为@RequestMapping(value = "/design", method = RequestMethod.POST)