Springboot从Thymeleaf选项获取对象

huangapple go评论59阅读模式
英文:

Springboot obtaining object from thymeleaf option

问题

以下是翻译的内容:

我正在尝试使用Spring Boot和Thymeleaf创建一个新的Product对象。我将一个包含Category的List<Category>传递给Thymeleaf,并在选项选择框中显示它们,以便在创建对象时进行选择。问题是对象被创建了,但是Category为null,我不确定为什么。

这是我的Product类的实例变量:

@Document(collection = "products")
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() {

    }
}

它有一个Category的实例变量:

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

    public Category() {

    }
}

这是创建Product选项的Thymeleaf代码,其中包含Category:

<form method="post" th:action="@{/products/add}" th:object="${product}" enctype="multipart/form-data">

以及控制器部分:

m.addObject("product", new Product());
<div class="widget-content widget-content-area">
    <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>

我有一个执行在product/add的POST按钮,这是用于它的REST 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 product,在我尝试打印所选的Category名称时,我得到一个NPE。我正在尝试从选项th:value="${cat}"中获取所选的Category,但是它不起作用。

英文:

So I am trying to create a new Product object with Springboot and Thymeleaf. I am passing in a List<Category> of categories into thymeleaf and displaying them in a option selection to be selected when the object is created. The issue is that the object is being created but the category is null and I am not sure why.

This is my products instance variables

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() {

    }

It has a instance variable for Category.

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

    public Category() {

    }

This is the thymeleaf code for the creation of the Product option where category is held.
&lt;form method=&quot;post&quot; th:action=&quot;@{/products/add}&quot; th:object=&quot;${product}&quot; enctype=&quot;multipart/form-data&quot;&gt;

and the controller
m.addObject(&quot;product&quot;, new Product());

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

I have a POST button that executes in the product/add
this is the rest API end point for it

    @RequestMapping(value = {&quot;/products/add&quot;}, 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(&quot;cat: &quot; + product.getCategory().getName());

It takes in a @Valid Product product
when I try to print out the category name which i selected I get an NPE.

I am trying to obtain the category selected from the option th:value=&quot;${cat}&quot;
but it is not working.

答案1

得分: 1

th:value="${cat}"更改为th:value="${cat.id}",在<option>中进行修改。原因是您正在分配th:value="${cat}"中类别对象的引用值,该值将不再存在于内存中。由于Spring将自动将ID转换为相应的对象,我们只需将ID分配给值。category=1将被转换为具有id=1new Category()

英文:

Short answer. Change th:value=&quot;${cat}&quot; to th:value=&quot;${cat.id}&quot; in &lt;option&gt;. The reason is you are assigning the reference value of category object in th:value=&quot;${cat}&quot; which will no longer exists in memory. Since spring will automatically convert the id to respective object, we just have to assign id to value. category=1 will be converted to new Category() with id=1

答案2

得分: 0

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

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

然后在Thymeleaf的部分中获取它,例如:

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

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

@Valid DtoClass dtoClass
英文:

You need to add the object to the model and view:

modelAndView.getModelMap().addAttribute(&quot;dto&quot;, dto);

and get it in the thymeleaf side, for example:

&lt;form th:action=&quot;@{/url}&quot; th:object=&quot;${dto}&quot; th:method=&quot;post&quot;&gt;
    &lt;input type=&quot;date&quot; th:field=&quot;${dto.date}&quot;&gt; 

Then you can recieve the filled object in the /url endpoint with:

@Valid DtoClass dtoClass

huangapple
  • 本文由 发表于 2020年9月1日 05:27:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63678401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定