【问题标题】:Redirect page in Spring Boot with Jpa and Thymeleaf使用 Jpa 和 Thymeleaf 在 Spring Boot 中重定向页面
【发布时间】:2020-09-10 22:11:32
【问题描述】:

我正在创建一对多关系,其中类别有许多产品。在列出我现有的所有类别后,我想查看特定类别中的所有产品并对这些产品(来自该类别)进行基本的 CRUD。 我发现在 Thymeleaf 中重定向页面有困难,最确切地说,我无法使用 Thymeleaf 访问“添加产品”页面。

@Entity
@Table(name="category")
public class Category {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id")
    private long id;

    @Column
    @NotEmpty(message = "*Please provide a description")
    private String description;

    @OneToMany(mappedBy = "category")
    private Set<Product> products;

    public Category(){}
@Entity
@Table(name="product")
public class Product {

    @Id
    @Column(name="id")
    private String id;

    @Column
    private String name;

    @Column
    private String description;

    @Column
    private float price;

    @Column
    private int discount;

    @Column
    private boolean isInStock;

    @ManyToOne
    @JoinColumn(name="category_id")
    private Category category;

这是我在服务层保存产品的方式

 public Product save(Product product, long id) {
        Category category = categoryRepository.getById(id);
        if (category != null) {
            product.setId(UUID.randomUUID().toString());
            product.setCategory(category);
            product.setInStock(false);
            return productRepository.save(product);
        } else {
            throw new ResourceNotFoundException("Category not found with id: " + id);
        }
    }

在控制器中我有:

@Autowired
    ProductService productService;

    @GetMapping("/products/{categoryId}")
    public String viewProducts(Model model, @PathVariable("categoryId") long categoryId) {
        List<Product> productsList = productService.findByCategoryId(categoryId);
        model.addAttribute("productsList", productsList);
        model.addAttribute("categoryId",categoryId );
        return "products";

    }
    @GetMapping("/newProduct/{categoryId}")
    public String showAddForm(Model model,@PathVariable("categoryId") long categoryId) {
        Product product = new Product();
        model.addAttribute("product", product);
        return "newProduct";
    }

    @PostMapping("/save/{categoryId}")
    public String addProduct(@ModelAttribute("product") Product product, @PathVariable long categoryId){
        productService.save(product, categoryId);
        return "redirect:products";
    }

我卡住的地方是我无法使用路径变量 categoryId 从 products.html 重定向到 newProduct.html(showAddForm 方法应该返回)。如果我手动输入 categoryId,它会将我重定向到错误页面在 URL 中,我终于找到了 newProduct.html。在 products.html 中,我有:

<body>
<div class="container my-2">
    <div class="card">
        <div class="card-body">
       <!-- TODO get category ID from categories  (parameters between HTML)-->
            <div th:switch="${productsList}" class="container my-5">

                <p class="my-5">
                    <a href="/product/newProduct/" class="btn btn-primary">Add product</a>
                </p>
                <div class="col-md-10">
                    <h2 th:case="null">No Products yet!</h2>
                    <div th:case="*">
                        <table class="table table-striped table-responsive-md">
                            <thead>
                            <tr>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Price</th>
                                <th>Discount</th>
                                <th>IsInStock</th>
                                <th>Edit</th>
                                <th>Delete</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="product : ${productsList}">
                                <td th:text="${product.name}"></td>
                                <td th:text="${product.description}"></td>
                                <td th:text="${product.discount}"></td>
                                <td th:text="${product.price}"></td>
                                <td th:text="${product.isInStock}"></td>
                                <td><a th:href="@{/product/edit/{id}(id=${product.id})}" class="btn btn-primary"></a></td>
                                <td><a th:href="@{/product/delete/{id}(id=${product.id})}" class="btn btn-primary"></a></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
</body>

</html>

【问题讨论】:

    标签: java spring-boot jpa thymeleaf one-to-many


    【解决方案1】:

    我看到的问题是,您的 showAddForm 代码和路径 @GetMapping("/newProduct/{categoryId}") 需要一个 catgoryID,它没有在上面的添加产品按钮中发送。由于您在 model.addAttribute("categoryId",categoryId ); 行中传递了 categoryId,因此您可以在 href 元素中使用它。因此,该链接应该类似于

    <p class="my-5">
        <a th:href="@{/product/newProduct(categoryId=${categoryId})}" class="btn btn-primary">Add product</a>
    </p>
    

    但是由于在方法showAddForm 中没有使用categoryID,所以你可以删除它。并尝试类似

    <p class="my-5">
        <a th:href="@{/product/newProduct}" class="btn btn-primary">Add product</a>
    </p>
    

    【讨论】:

    • 谢谢!基本上将类别 ID 本身传递给 html 是我的问题,以便使用您提出的解决方案,因为我想我必须将 Category 对象带入 html 我们只使用 Product 对象。抱歉这个愚蠢的问题,这只是我第一次尝试使用百里香,我正在基于互联网上已经找到的示例构建自己的版本。
    • @AlexandraDediu 您实际上是在viewProducts 方法中传递categoryId。我没有看到。我已经编辑了我的答案。这个解决方案应该可以工作。告诉我
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2018-04-16
    • 2018-03-23
    • 2018-01-24
    • 2023-03-29
    相关资源
    最近更新 更多