【问题标题】:How to get object from model?如何从模型中获取对象?
【发布时间】:2017-04-12 17:53:49
【问题描述】:

首先对不起我的英语。 我创建了一个 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

【问题讨论】:

    标签: java html controller thymeleaf crud


    【解决方案1】:

    有几件事需要处理。

    您需要告诉 Thymeleaf 您的模型属性对象以及理想情况下它应该如何绑定到它。在表单标签中添加th:object,在输入标签中添加th:field。我还怀疑你会想要一个@PostMapping 作为你最后一个方法中的逻辑。

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

    【讨论】:

    • 感谢您的回答。我确定页面代码的措辞有误。我不知道如何正确编写它,以便它按照推送购买的原则工作。上面,我添加了一张应该如何工作的图片。你能告诉我如何正确地制定代码吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多