【问题标题】:Springboot obtaining object from thymeleaf optionSpringboot 从 thymeleaf 选项中获取对象
【发布时间】:2020-12-20 00:30:53
【问题描述】:

所以我正在尝试使用 Springboot 和 Thymeleaf 创建一个新的 Product 对象。我将一个类别列表传递到 thymeleaf 中,并在创建对象时选择的选项中显示它们。问题是正在创建对象,但类别为空,我不知道为什么。

这是我的产品实例变量

public class Product {
    @Id
    private String id;
    private String name, description;
    private double price;
    private Binary image;
    private Category category;
    private ProductStatus status;

    public Product() {

    }

它有一个类别的实例变量。

@Document(collection = "categories")
public class Category {
    @Id
    private String id;
    private String name, description;

    public Category() {

    }

这是用于创建包含类别的产品选项的百里香代码。 <form method="post" th:action="@{/products/add}" th:object="${product}" enctype="multipart/form-data">

和控制器 m.addObject("product", new Product());

                            <div class="input-group mb-6">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">Product Category</span>
                                </div>
                                <select th:field="*{category}">
                                    <option th:each="cat : ${categories}"
                                            th:value="${cat}"
                                            th:text="${cat.getName()}">Wireframe</option>
                                </select>
                            </div>
                        </div>

我有一个在产品/添加中执行的 POST 按钮 这是它的其余 API 端点

    @RequestMapping(value = {"/products/add"}, method = RequestMethod.POST)
    public ModelAndView addProduct(ModelAndView m, @Valid Product product, MultipartFile file) throws IOException {
        User admin = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        System.out.println("cat: " + product.getCategory().getName());

它包含一个@Valid Product 产品 当我尝试打印出我选择的类别名称时,我得到了一个 NPE。

我正在尝试获取从选项th:value="${cat}" 中选择的类别 但它不起作用。

【问题讨论】:

    标签: java spring-boot spring-mvc thymeleaf


    【解决方案1】:

    简短的回答。在&lt;option&gt; 中将th:value="${cat}" 更改为th:value="${cat.id}"。原因是您在th:value="${cat}" 中分配了类别对象的引用值,该值将不再存在于内存中。由于 spring 会自动将 id 转换为相应的对象,我们只需将 id 分配给 value。 category=1 将转换为 new Category()id=1

    【讨论】:

      【解决方案2】:

      您需要将对象添加到模型和视图中:

      modelAndView.getModelMap().addAttribute("dto", dto);
      

      把它放在百里香一边,例如:

      <form th:action="@{/url}" th:object="${dto}" th:method="post">
          <input type="date" th:field="${dto.date}"> 
      

      然后您可以在 /url 端点中接收填充的对象:

      @Valid DtoClass dtoClass
      

      【讨论】:

      • 封装我确实有这个。
        在控制器中我有这个 m.addObject ("产品", new Product());
      • 使用modelAndView.getModelMap().addAttribute(
      猜你喜欢
      • 2017-08-26
      • 2018-04-25
      • 2018-04-11
      • 2018-08-08
      • 2021-08-01
      • 2017-08-16
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多