【问题标题】:How can I collect object using thymeleaf?如何使用百里香收集对象?
【发布时间】:2019-06-01 23:53:39
【问题描述】:

问题:当我提交表单时,服务器报告:“无法将 java.lang.String[] 类型的属性值转换为属性成分所需的 java.util.List 类型”。

我的猜测:我认为问题在于收集的属性成分是字符串。 我使用百里香作为前端。

问题:如何使用百里香叶收集成分?

DOMAIN Taco:
private String name;
private List<Ingredient> ingredients;


DOMAIN Ingredient: 
private final String id;
private final String name;
private final Type type;
public static enum Type{
    WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
}

CONTROLLER:
import taco.Ingredient.Type;

//method to show design
public String showDesign(Model model) {
List<Ingredient> ingredients = new ArrayList<>();
ingredientRepo.findAll().forEach(i-> ingredients.add(i));

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

model.addAttribute("taco", new Taco());

    return "design";
}

//method that is used to handle the post request
@PostMapping
public String processDesignForm(Taco taco) {
    log.info("process taco: "+taco);

    return "redirect:/orders/current";
}


DESIGN(use thymeleaf):
<form method="POST" th:object="${taco}">
    <div th:each="ingredient : ${wrap}">
        <input name="ingredients" type="checkbox" 
               th:value="${ingredient.id}" />
    </div>
</form>

【问题讨论】:

  • 能否请您在控制器中发布用于处理发布请求的代码?
  • @Periklis Douvitsas 我已经添加了

标签: java spring spring-boot spring-mvc thymeleaf


【解决方案1】:

您可以执行以下操作,将选择的 id(成分)作为 RequestParam

@PostMapping
public String processDesignForm(Taco taco, @RequestParam("ingredients") List<String> idIngredients) {
    log.info("process taco: "+taco);

    if(idIngredients != null){
        for(String id : idIngredients){
            ...//handle it
         } 
    }
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2015-05-18
    • 2016-07-29
    • 2021-01-25
    • 2019-08-10
    相关资源
    最近更新 更多