java - Thymeleaf 返回 String 数组而不是 List<Object>

标签 java spring thymeleaf

我正在学习如何使用 Spring Boot 和 Thymeleaf。我遇到一个问题,我向 Thymeleaf 页面提供表单列表中特定对象的列表。当用户选择值并发布结果时,结果是所选对象的字符串,并且与我想要存储值的对象不兼容。

这听起来可能有点拗口,所以下面是代码。

我的问题是:是否有办法确保 Thymeleaf 返回对象列表?

输入:一个类将一堆成分传递到表单 该类将 Ingredient 类的列表传递给表单(过滤对此并不重要 - 插入列表作为模型属性的值,键是成分类型)

@GetMapping
public String showDesignForm(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));
    }   
    model.addAttribute("taco", new Taco()); 
    return "design";
}

Thymeleaf 获取该列表并将其显示在复选框中

<!DOCTYPE html>
<html
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
<link rel="stylesheet" th:href="@{/styles.css}" />
</head>
<body>
<h1>Design your taco!</h1>
<img th:src="@{/images/TacoCloud.png}"/>
<form method="POST" th:object="${taco}">
<div class="grid">
<div class="ingredient-group">
<h3>Designate your wrap:</h3>
<div th:each="ingredient : ${wrap}">
<input name="ingredients" type="checkbox" th:value="${ingredient}" />
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group">
<h3>Pick your protein:</h3>
<div th:each="ingredient : ${protein}">
<input name="ingredients" type="checkbox" th:value="${ingredient}" />
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group">
<h3>Choose your cheese:</h3>
<div th:each="ingredient : ${cheese}">
<input name="ingredients" type="checkbox" th:value="${ingredient}" />
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group">
<h3>Determine your veggies:</h3>
<div th:each="ingredient : ${veggies}">
<input name="ingredients" type="checkbox" th:value="${ingredient}" />
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group">
<h3>Select your sauce:</h3>
<div th:each="ingredient : ${sauce}">
<input name="ingredients" type="checkbox" th:value="${ingredient}" />
<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>

目标类:期望返回值为List

package tacos;

import java.util.Date;
import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class Taco {

    private Long id;

    private Date createdAt;

    @NotNull
    @Size(min=5, message="Name must be at least 5 characters long")
    private String name;
    @Size(min=1, message="You must choose at least 1 ingredient")
    private List<Ingredient> ingredients;
}

错误:

Field error in object 'taco' on field 'ingredients': rejected value [Ingredient(id=FLTO, name=Flour Tortilla, type=WRAP),Ingredient(id=CHED, name=Cheddar, type=CHEESE)]; codes [typeMismatch.taco.ingredients,typeMismatch.ingredients,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [taco.ingredients,ingredients]; arguments []; default message [ingredients]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.List' for property 'ingredients'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'tacos.Ingredient' for property 'ingredients[0]': no matching editors or conversion strategy found]

最佳答案

我在一些代码中遇到了同样的问题,但我通过使用 Spring JPA 克服了它。但如果您使用的是 Spring JPA 以外的其他版本,则可以在您的应用程序中使用此转换器。根据您的代码,Ingredient 的属性 id 是 String。所以代码将是。

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

private final IngredientRepo ingredientRepo;

@Autowired
public IngredientConverter(IngredientRepo ingredientRepo) {

    this.ingredientRepo = ingredientRepo;
}

@Override
public Ingredient convert(String source) {

      List<Ingredient> ingredients = new ArrayList<>();

      ingredientRepo.findAll().forEach(i -> ingredients.add(i));

      for (Ingredient ingredient : ingredients) {

        // You may use equal() method
        if (ingredient.getId() == source)

            return ingredient;
      }

      return null;
   }

}

关于java - Thymeleaf 返回 String 数组而不是 List<Object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51024877/

相关文章:

java - 如何修复使用 Thymeleaf 调用 Java 方法?

template-engine - 如何防止thymeleaf替换HTML属性值中的特殊字符?

java - 在 Spring Boot 中使用 Java 配置在 bean 定义之外为 bean 别名

java - Wicket 和 Spring 集成

java - setVelocity引擎无法应用于org.springframework.ui.velocity.VelocityEngineFactoryBean

spring - 手动获取 AuthenticationManager 实例

spring - Spring 安全编译错误

java - Spring Boot + Thymeleaf 的@WebAppConfiguration 和@ContextConfiguration

java - NullpointerException 尝试调用虚拟方法 'void android.widget.Button.setOnClickListener

java - Android Studio 未知类