无法将从控制器传递到thymeleaf html的模型属性传递回另一个控制器

时间:2019-07-30 12:19:01

标签: jquery spring-boot thymeleaf

我已将控制器的modelAttribute“ authRequest”传递给“ dashboard.html”。我想从“ dashboard.html”中单击“查看卡片”按钮来调用另一项服务。还希望将modelAttribute“ authRequest”传递回视图卡控制器,以便在“ viewCards.html”中获得modelAttribute“ authRequest”。我尝试给出th:href和form-action,但无法在视图卡控制器中(因此在“ viewCards.html”中)获得“ authRequest”的值。如何将modelAttribute“ authRequest”传递给viewCards控制器? 试图通过modelAttribute如下

<form action="#" th:action="@{/viewCards}" th:object="${authRequest}" method="post">
    <input type="submit" value="View cards" /></form>

也尝试过href

<a th:href="@{/viewCards}" th:object="${authRequest}">view Cards</a>

dashboard.html-在这里,我可以获得$ {authRequest.userName}“的价值

<form action="#" th:action="@{/viewCards}" th:object="${authRequest}" method="post">
    <input type="submit" value="View cards" />
</form>

 <p th:text="'User Name:   ' + ${authRequest.userName}" />

viewCards.html-无法获得$ {authRequest.userName}的价值

<script type="text/javascript" th:src="@{/webjars/jquery/1.9.1/jquery.min.js/}"></script>
 <script th:inline="javascript">
    var user= [[${authRequest.userName}]];
 </script>
  <script type="text/javascript"  th:src="@{/vCards.js}"></script>

 <p th:text="'User Name:   ' + ${authRequest.userName}" />

控制器

@RequestMapping(value= "/virtualWallet/login" , method= RequestMethod.POST)
public String getAuthResponse(
        @ModelAttribute AuthRequest authRequest,
        Model model
        ){

            String resp = authService.getAuthResponse(authRequest);

            if(resp.equals("Success")) {
                return "dashboard";

            }
            return null;
        }

@RequestMapping(value= "/viewCards" , method = RequestMethod.POST)
public String viewCards(
        @ModelAttribute AuthRequest authRequest
        ) {
            return "viewCards";}

预期在“ viewCards.html”中获取“ authRequest”值。我变得空了。

1 个答案:

答案 0 :(得分:0)

您的第一种方法几乎是正确的。

<form th:action="@{/viewCards}" th:object="${authRequest}" method="post">
    <input type="text" th:value="*{authRequestAttr1}" th:field="*{authRequestAttr1}" hidden/>
    <!-- Add the rest of authRequest attributes here in the same fashion -->

    <button type="submit"></button>
</form>

要提交th:object中的对象,您需要输入包含该对象中属性值的输入。您还需要将它们与th:field绑定。

由于您只想将该对象传递给控制器​​,因此在该示例中,我隐藏了输入,但这不是必需的。