2017-04-12 100 views
0

首先是我的英语。 我创建了一个CRUD项目,您可以在其中创建用户和游戏。用户有钱可购买游戏并添加到您的图书馆。在这个过程中,我遇到了一个问题。我无法从控制器中的模型中获取对象。可能是什么问题呢?如何从模型中获取对象?

控制器

@RequestMapping("/user-profile/{id}") 
public String getUserProfile(@PathVariable Integer id, Model model) { 
    logger.debug("Received user data"); 
    model.addAttribute("user", userDAO.findOne(id)); 
    model.addAttribute("gameLib", userDAO.findOne(id).getGames()); 
    return "user/userProfile"; 
} 

@RequestMapping(value = "/order-list") 
public String getOrderGameList(@ModelAttribute("user") User user, Model model) { 
    logger.debug("Received order list for user"); 
    model.addAttribute("user", user); 
    model.addAttribute("games", gameDAO.findAll()); 
    return "order/order-form"; 
} 

@RequestMapping(value = "/order-list/{gameId}") 
public String postOrderGameList(@ModelAttribute("user") User user, @PathVariable Integer gameId) { 
    logger.debug("Add game in user library"); 
    Game game = gameDAO.findOne(gameId); 
    logger.debug("Ordering game"); 
    user.setWallet(user.getWallet() - game.getPrice()); 
    user.getGames().add(game); 
    if (user.getWallet() < game.getPrice()) { 
     logger.debug("Ordering failed"); 
    } else { 
     logger.debug("Ordering game"); 
     user.setWallet(user.getWallet() - game.getPrice()); 
     user.getGames().add(game); 
    } 
    return "redirect:/user-profile/{" + user.getId() + "}"; 
} 

HTML

<h2>Games</h2> 
<table class="list"> 
    <thead> 
    <tr> 
     <th>ID</th> 
     <th>NAME</th> 
     <th>Description</th> 
     <th>Type</th> 
     <th>Year</th> 
     <th>Price</th> 
     <th></th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr th:each="game : ${games}"> 
     <td th:text="${game.id}"></td> 
     <td th:text="${game.name}">Game</td> 
     <td th:text="${game.description}">Description</td> 
     <td th:text="${game.gameType}">type</td> 
     <td th:text="${game.year}">2017</td> 
     <td th:text="${game.price}">0</td> 
     <td> 
      <form th:action="@{/users/order-list/} + ${game.id}" method="post"> 
       <input type="submit" th:value="Buy"/> 
      </form> 
     </td> 
    </tr> 
    </tbody> 
</table> 

这是link到整个项目

UPD

App VIEW

回答

0

有几件事情需要努力。

您需要告诉Thymeleaf关于您的模型属性对象,理想情况下它应该如何绑定它。将th:object添加到表单标记并将th:field添加到输入标记。我也怀疑你会希望@PostMapping为您的最后一种方法的逻辑。

旁白: @RequestMapping(value = "/order-list")可以因为只有一个列表中的值缩短到 @RequestMapping("/order-list")。我还假设你在整个代码中对NPE进行相关检查。

+0

谢谢你的回答。我确定在页面代码的措辞中存在错误。我不知道如何正确书写,以便按推买原则工作。上面,我添加了一张如何工作的图片。你能告诉我如何正确地编写代码吗? –

+0

浏览http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#creating-a-form – bphilipnyc