【发布时间】:2019-02-16 11:04:33
【问题描述】:
Thymeleaf 无法显示和解析我的对象。我想,我在 html 文件中做错了。请检查一下
public class Ingredient {
private final String id;
private final String name;
private final Type type;
public static enum Type {
WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
}
塔可课
public class Taco {
private String name;
private List<String> ingredients;
}
控制器类
@Slf4j
@Controller
@RequestMapping("/design")
public class DesignTacoController {
@ModelAttribute
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
public String showDesignForm(Model model) {
model.addAttribute("design", new Taco());
return "design";
}
@PostMapping
public String processDesign(@Valid @ModelAttribute("design") Taco design, Errors errors, Model model) {
if (errors.hasErrors()) {
return "design";
}
log.info("Processing design: " + design);
return "redirect:/orders/current";
}
private List<Ingredient> filterByType(
List<Ingredient> ingredients, Type type) {
return ingredients
.stream()
.filter(x -> x.getType().equals(type))
.collect(Collectors.toList());
}}
HTML。只是其中的一部分,我认为问题就在其中。看起来您的帖子主要是代码;请添加更多详细信息。看起来您的帖子主要是代码;请添加更多详细信息。
<form method="POST" th:object="${design}">
<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>
【问题讨论】:
-
抱歉,第一次发的不好,所以..
-
主机无法显示控制器提供给 html 页面的对象。我想,我在 html 中写错了
-
看不到哪个模型属性?
-
idea 无法解析我给出的这个小 html 中的“protein”、“ingredient.id”和“ingredient.name”
-
看我的回答。我想你误解了如何使用 ModelAttribute 方法。