从百里香叶表中选择一个物体,然后通过百里香叶将其传回控制器

时间:2018-01-17 18:10:42

标签: spring thymeleaf

我在百里香叶中有一个对象表,每个对象数据旁边都有连接按钮,我想知道是否可以这样做,当用户点击他们想要的行旁边的“加入”时,它会将所选对象发送到控制器。

以下是我的内容,但我知道它不正确,因为我在控制器中收到空指针异常。

th:each="team : ${teams}"
 th:text="${team.teamName}"
 th:text="${team.teamAddress}"
 th:text="${team.level}"
     th:text="${team.manager}"></td>
    <button onclick="myFunction()">View Team</button>  

         th:action="@{/jointeam}" method="post" th:object="${team}"

        <button onclick="myFunction()">Join Team</button>

我的控制器代码:

   @RequestMapping(value="/jointeam", method=RequestMethod.POST)
   public String joinTeam(@Valid Team team, Principal principal)
   {


//     String userName = (SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();

       Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
       String email = loggedInUser.getName();


       UserLogin user = userRepository.findByEmail(email);

       team.addUserLogin(user);


               return "parseGame";
   }

1 个答案:

答案 0 :(得分:1)

正如我在评论中所建议的那样,你可以这样做:

th:each="team : ${teams}"
 th:text="${team.teamName}"
 th:text="${team.teamAddress}"
 th:text="${team.level}"
     th:text="${team.manager}"></td>
    <button onclick="myFunction()">View Team</button>  

         th:action="@{/jointeam/} + ${team.id}"

        <button onclick="myFunction()">Join Team</button>

@RequestMapping(value = "/jointeam/{teamId}", method = RequestMethod.GET)
public String joinTeam(@PathVariable("team") Long teamId, Principal principal) {

   Team team = teamRepository.findOne(teamId); // Do whatever you want with team
   // String userName = (SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();

   Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
   String email = loggedInUser.getName();

   UserLogin user = userRepository.findByEmail(email);

   team.addUserLogin(user);
   return "parseGame";
}

请注意,这是一个GET调用。您可能希望将其保留为POST调用并创建一个触发joinTeam方法的ajax函数。