Java Spring - Thymeleaf возвращает нулевой объект в контроллер - PullRequest
0 голосов
/ 29 мая 2018

У меня есть страница, которая содержит информацию о результатах калькулятора в базе данных.Когда я пытаюсь щелкнуть кнопку на следующей странице, если я проверю более подробную информацию, тогда исключение java catch:

The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!

Почему у меня эта ошибка?

Мои контроллеры:

@GetMapping("/form")  
    public String selectData(Model model){  
        model.addAttribute("calcResults", calculatorRepository.findAll());
        return "user/form";  
    } 

-

@PostMapping("/show")
public String showDetails(@ModelAttribute(value = "calcResults") CalculatorResult calcResults,Model model){
    System.out.println(calcResults.getId());
    model.addAttribute("calcResults", calculatorRepository.findOne(calcResults.getId()));
    return "user/show";
} 

-

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html xmlns="http://www.w3.org/1999/xhtml" 
      xmlns:th="http://www.thymeleaf.org">
    <head>
        <link rel="stylesheet" href="style.css" type="text/css"/>
        <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  ></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/printThis/1.12.3/printThis.js"></script>

        <title>Result</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link type="text/css" rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </head>
    <body>
            <form action="#" th:action="@{/show}" th:object="${calcResults}" method="post">
            <div class="col-md-4">
        <h1>Historia</h1>
            </div>

            <div style="padding:0 20px"/>

                <table class="table table-striped">
                        <tr>
                            <th>ID</th>
                            <th>Data Wyjazdu</th>
                            <th>Data Przyjazdu</th>
                            <th>Akcja</th>
                        </tr>  
                <tr th:each = "calc : ${calcResults}">
                        <td th:text="${calc.id}"></td>
                        <td th:text="${#dates.format(calc.dataWyjazdu, 'dd-MM-yyyy')}"></td>
                        <td th:text="${#dates.format(calc.dataPrzyjazdu, 'dd-MM-yyyy')}"></td>

                        <td>
                            <button type="submit" class="btn btn-success btn-xs">Przelicz</button>
                            <!--<a th:href="@{/sucess}" class="btn btn-success btn-xs">Szczegóły</a>-->
                        </td>
                </tr>
            </table>
            </form>
    </body>
</html>

1 Ответ

0 голосов
/ 29 мая 2018

Ваша привязка неверна.Вам не хватает двух вещей:

  1. Используйте атрибут th: field вместо атрибута th: text.Вот почему id не привязывается к соответствующему объекту.
  2. Похоже, объект привязывается к "calcResults" - это список объектов.Я никогда не делал так.Я думаю, что динамическое связывание вообще не работает.Обходной путь: Создайте класс-оболочку CalcResult, которая имеет свойство массива, например, вызываемые элементы (заменяя ваш список) ... + следующий код:

    <tr th:each="calc, stat : *{items}">
      <input type="text"
         th:field="*{items[__${stat.index}__].id}">
      /* other fields of the objects stored in the array has to be insert here like in the line above */
    </tr>
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...