gpt4 book ai didi

java - 如何动态调整列表类型变量的输入?

转载 作者:行者123 更新时间:2023-12-01 18:53:30 26 4
gpt4 key购买 nike

我正在使用 Java 开发 Spring Boot 的初学者项目,使用 Hibernate、JPA 和 Thymeleaf。我有一个Post具有 3 个重要变量的实体:String title , String contentList<Tag> tags 。其次,我有一个表单,用于创建新的 Post实体。如您所见,我在调整String title的输入时没有任何问题。和 String content ,但我不知道,如何让用户输入tags帖子的内容。

Post.java:

@Entity
@Table(name = "post")
public class Post {

@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@Column(name = "postId")
private Integer postId;

@Column(name = "title")
private String title;

@Column(name = "content")
private String content;

@ManyToMany
@JoinTable(name="postTag", joinColumns = { @JoinColumn(name = "postId") }, inverseJoinColumns = { @JoinColumn(name = "tagId") })
private List<Tag> tags = new ArrayList<Tag>();

public Post() {
}

public Integer getPostId() {
return postId;
}

public void setPostId(Integer id) {
this.postId = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public List<Tag> getTags() {
return tags;
}

public void setTags(List<Tag> tags) {
this.tags = tags;
}

}

Important part of PostController.java

@GetMapping("/add")
public String addPostForm(Model model, Post post) {
model.addAttribute("post", post);
model.addAttribute("tags", post.getTags());
return "add-post";
}

@PostMapping("/add")
public String addPostProcess(@ModelAttribute("post") Post post, Model model) {
postService.savePost(post);

//return the page, what will display the posts
}

Important part of add-post.html

<form action="#" th:action="@{/posts/add}" th:object="${post}" method="post">
<input type="text" th:field="*{title}" id="title" />
<textarea th:field="*{content}" id="content"></textarea>

<div th:each="tag : ${tags}">
<input type="text" th:field="*{tag.name}" id="tag">
</div>

<div th:each="item, tag : ${tags}">
<input th:field="${tags[__${tag.index}__].name}" type="text"/>
</div>

<input type="submit" value="Add post" />
</form>

我该怎么做?

最佳答案

您应该在 th:field 标记中使用星号而不是美元:

<input th:field="*{tags[__${tag.index}__].name}" type="text"/>

关于java - 如何动态调整列表类型变量的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com