如何从模型中获取对象?

时间:2017-04-12 17:53:50

标签: java html controller thymeleaf crud

首先为我的英语而烦恼。 我创建了一个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

1 个答案:

答案 0 :(得分:0)

有一些事情需要发挥作用。

你需要告诉Thymeleaf你的模型属性对象,理想情况是它应该如何绑定它。将th:object添加到表单标记,将th:field添加到输入标记。我也怀疑你在上一个方法中需要一个@PostMapping的逻辑。

<强>除了: @RequestMapping(value = "/order-list")可缩短为。{1}} @RequestMapping("/order-list")因为列表中只有一个值。我还假设您在整个代码中对NPE进行相关检查。