2017-07-25 111 views
1

我正在運行一個Spring Boot項目,我試圖傳遞一個id或使用post方法的對象,但我一直爲用戶返回null。我希望使用戶可用,以便在創建摘要頁面時(post方法針對單獨的表單),我從中獲得的用戶可以添加到摘要對象中。如何將我的Thymeleaf模板的隱藏值傳遞給控制器​​(Spring Boot)?

我也相信有可能通過錨鏈接傳遞id的方式?

這是我的html:

 <div > 
     <span th:text="${user.firstName}"></span> Summary Page 
      <span th:text="${user.emailAddress}"></span> 
      <form id="add" th:action="@{/addSummary}" method="post"> 
       <input id="userId" name="${user.userId}" type="hidden" value="${userId}"/> 
      <!-- <input id="userId" name="${user}" type="hidden" value="${user}"/> --> 
       <button type="submit" value="save">Add Summary</button> 
      </form> 
     </div> 
<!-- another way to pass id? --> 
<!--<a href="createSummary.html?user.id">AddSummary</a>--> 

控制器:

@RequestMapping(value ="/addSummary", method = RequestMethod.POST) 
public ModelAndView addSummary(User user) { 

    try{ 
     ModelAndView model = new ModelAndView("views/createSummary"); 
     System.out.println("======POST Summary Method hit====="); 
    // model.addObject("summary", new Summary()); 
     User nUser = userService.findById(user.getUserId()); 
     model.addObject("user", nUser); 
     System.out.println("user: " + nUser.getUserId()); 
     return model; 
    }catch(Exception ex){ 
     System.out.println(ex.toString()); 
     throw ex; 
    } 
} 

任何幫助或建議,將不勝感激! - 謝謝

+0

錨將導致HTTP Get請求,並且相應的Controller方法需要使用@RequestParam指定用戶標識。如果這是你問的問題? –

+0

...並且不應該使用你的'value =「$ {userId}」''= value =「$ {user.userId}」 - 與thymeleaf_不一樣,在這種情況下,它的ID將被傳遞給控制器不是用戶。 –

+0

@TonyKennah謝謝,我也試過,但我沒有收到任何迴應。爲了在鏈接中傳遞id,我想知道是否可以做一些事情,比如傳遞來自已經在頁面上的對象(用戶)的id並將其發送給控制器。 – BluLotus

回答

0

首先,您的代碼的核心問題是您嘗試在非Thymeleaf屬性中使用Thymeleaf表達式,它不會按預期工作。 Thymeleaf只會查看以th:開頭的屬性(如果使用HTML5語法,則爲data-th-)。

對於你的情況,我會用th:objectth:field

<form id="add" th:action="@{/addSummary}" method="post" th:object="${user}"> 
    <input id="userId" th:field="*{userId}" type="hidden"/> 
    <button type="submit" value="save">Add Summary</button> 
</form> 

參考:Creating a Form in the Thymeleaf + Spring tutorial

+0

當然啊!謝謝,holmis83! – BluLotus

相關問題