【问题标题】:Not able to pass model Attribute passed from controller to thymeleaf html back to another controller无法将从控制器传递到 thymeleaf html 的模型属性传递回另一个控制器
【发布时间】:2019-12-07 20:06:05
【问题描述】:

我已将模型属性“authRequest”从控制器传递到“dashboard.html”。从“dashboard.html”我想在单击“查看卡片”按钮时调用另一个服务。还想将modelAttribute“authRequest”传递回视图卡控制器,以便我将在“viewCards.html”中获取modelAttribute“authRequest”。我尝试给出 th:href 和 form-action 但无法在视图卡控制器中获得“authRequest”的值,因此无法在“viewCards.html”中获得。如何将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”值。我要空了。

【问题讨论】:

    标签: jquery spring-boot thymeleaf


    【解决方案1】:

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

    <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 绑定它们。

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

    【讨论】:

    • 稍作改动即可正常工作。输入 type="hidden" 。谢谢你。
    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多