Thymeleaf returning a String array instead of List<Object>

Christopher Barrett :

I am learning how to use Spring Boot and Thymeleaf. I have an issue where I provide a list of a specific Objects in the Form List to the a Thymeleaf page. When the user selects the values and posts the results, the result is a String of the selected objects and incompatible with the Object I wanted to store the values in.

This may sound like a mouthful so below is the code.

My question is: Is there anyway to ensure that Thymeleaf returns a List of Objects?

Input: A class passes a bunch of Ingredients to the form This class passes in a List of class Ingredient to the form (The filtering does not matter for this - A list is inserted as the value of the model attribute, with the key being a type of 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 takes that list and displays it in checkboxes

<!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>

Destination class: Expects the returned value to be 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;
}

Error:

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]

Christopher Barrett :

I came across a video which helped create a converter between the String result of the Thymeleaf page and the POST method in Spring.

https://www.youtube.com/watch?v=e9mlrHyn73w&t=627s

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Convert object array string to list string

ThymeleafがList <Object>ではなくString配列を返す

Laravel getCountForPagination() returning Object instead of int

How to correctly bind checkbox to the object list in thymeleaf?

ThymeleafのList<Map<String、Object>>マップを反復処理します

Python CSV library returning 1 item instead of a list of items

Looping an object with an string array

Ruby String variable returning true for .is_a?(Array)

Storing a string array in a class member function and returning it

How to return object instead of string for response with nock?

How to return array instead of object in laravel 5

JProperty Converting to String instead of Array of Objects

NSMutableArray to NSString conversion provides array instead of string

Deserializing Xml string into object with List<>

React JS - JSX returns [object Object] instead of string

How to cast a list of String to a list of Object

Why are some methods in the Android SDK accept an array as a parameter instead of returning an array?

string array inside object array in Powershell

Return as JSON string array instead of Key-Value array

How to join an array of values by returning each value as a separate string?

MVC 6 WebAPI returning html error page instead of json version of exception object

Thymeleaf Without Object Classes?

Passing an object into a Thymeleaf fragment

Converting String Array list to char array

thymeleaf and condition and list size

Why Django's related_model property is returning string instead of Model instance?

Expected 'property' to be of type string, instead found type object - Dynamoose

Getting string instead of Carbon Object when fetching data

AngularJS - Expected response to contain an object but instead got an array

TOP 一覧

  1. 1

    PictureBoxで画像のブレンドを無効にする

  2. 2

    HTTPヘッダー 'SOAPAction'の値はサーバーによって認識されませんでした

  3. 3

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  4. 4

    レスポンシブウェブサイトの一番下にスティッキーなナビゲーションバーを作成するのに問題がある

  5. 5

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  6. 6

    Ansibleで複数行のシェルスクリプトを実行する方法

  7. 7

    Python / SciPyのピーク検出アルゴリズム

  8. 8

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  9. 9

    ZScalerと証明書の問題により、Dockerを使用できません

  10. 10

    Rパッケージ「AppliedPredictiveModeling」のインストール中にエラーが発生しました

  11. 11

    テキストフィールドの値に基づいて UIslider を移動します

  12. 12

    Crashlytics:コンパイラー生成とはどういう意味ですか?

  13. 13

    「埋め込みブラウザのOAuthログイン」を有効にしてコールバックURLを指定した後でも、Facebookのコールバックエラーが発生する

  14. 14

    tf.nn_conv2dとtf.nn.depthwise_conv2dの違い

  15. 15

    CSSはアニメーションで変換および回転します

  16. 16

    BLOBストレージからデータを読み取り、Azure関数アプリを使用してデータにアクセスする方法

  17. 17

    Chromeウェブアプリのウェブビューの高さの問題

  18. 18

    Postmanを使用してファイル付きの(ネストされた)jsonオブジェクトを送信する

  19. 19

    amCharts 4で積み上げ棒グラフの輪郭を描く方法は?

  20. 20

    Officeアドインを使用してOutlookの連絡先のリストにプログラムでアクセスすることは可能ですか?

  21. 21

    Reactでclsxを使用する方法

ホットタグ

アーカイブ