2017-07-25 114 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

相关问题