物业或油田'产品'无法找到null:each

时间:2018-05-12 10:23:13

标签: java html spring thymeleaf

我有一个关于百里香的问题

这是我的产品总监:

@GetMapping(path = "/search_results")
  public String search(@RequestParam(value = "search", required = false) String search, Model model){
    List<Product> productList = productRepository.findAll();

    for (Product product : productList) {
      System.out.println("Product ID: " + product.getID_product());
      if (product.getProdName().contains(search) || product.getProdBrand().contains(search)){
        model.addAttribute("price", product.getPrice());
        System.out.println("Price: " + product.getPrice());
        model.addAttribute("prodName", product.getProdName());
        System.out.println("Name: " + product.getProdName());
        model.addAttribute("category_name", product.getCategory().getCategory_name());
        System.out.println("Category: " + product.getCategory().getCategory_name());
        model.addAttribute("prodDesc", product.getProdDesc());
        model.addAttribute("prodImage", product.getProdImage());
        model.addAttribute("prodBrand", product.getProdBrand());
      }
    }
    return "search_results";
  }

这是我的HTML上的一些片段: 搜索框:

<form method="get" action="/search_results" th:action="@{/search_results}" th:object="${productController}"/>
          <input th:text="${search}" class="col-8.5" type="text" id="search" name="search"
                 placeholder="Search for Products and Brands">
          <input id="searchButton" class="navbar-toggler" type="submit" value="Search"/>
        </form>

和搜索结果卡:

<div class="card h-20">
                <a th:href="@{/item_details}"><img class="card-img-top" th:blob="${prodImage}" alt="image"></a>
                <div class="card-body" th:each="product : *{products}">
                  <h4 class="card-title">
                    <a th:href="@{/item_details}" th:text="${product.prodName}"/>
                  </h4>
                  Rp:
                  <span text="price" th:text="${product.price}"/><br>
                    Category:
                  <a text="category_name" th:text="${product.category_name}" name="category_name"/>
                </div>
                <div class="card-footer">
                  <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small>
                </div>
              </div>

但是当我输入搜索项时,它会出现这个错误:

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'products' cannot be found on null.

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您忘记将产品插入到您的模型属性中。 你应该在你的控制器中有类似的东西

List<Product> productList = productRepository.findAll();
model.addAttribute("products", productList);