【发布时间】:2020-11-20 18:43:40
【问题描述】:
我有一个小项目,我可以在我的 SQL 数据库中的表中添加类别。 我有另一张表叫做 products。 在“/addProducts”屏幕中,我希望在我的表单中出现一个下拉菜单。 我希望从我的数据库中的“类别”表中的数据填充下拉列表。 但目前我做不到。
因此,如果有人可以帮助我提供一些 thymleaf/html 代码以在我的表单中显示数据,我将不胜感激。
非常感谢任何建议。
PS 我没有使用 DAO 类,也不想硬编码这些值。 只是希望能够直接从数据库中获取数据并将其显示在表单的下拉列表中。谢谢:
1 类别控制器
@Slf4j
@Controller
public class CategoryController implements Serializable {
private CategoryRepository categoryRepository;
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
@Autowired
CategoryRepository service;
@Autowired
private UserRepository userRepository;
@GetMapping("/category")
public String displayCategory(Model model) {
model.addAttribute("category", service.findAll());
return "/category";
}
@GetMapping("/categoryUserView")
public String displayCategoryUser(Model model) {
model.addAttribute("category", service.findAll());
return "/categoryUserView";
}
@PostMapping("/addCategory")
public String processOrder(@Valid Category category, BindingResult result, SessionStatus
sessionStatus, Model model) {
if (result.hasErrors()) {
return "addCategory";
}
service.save(category);
model.addAttribute("category", service.findAll());
return "category";
}
@GetMapping("/editCategory/{id}")
public String showUpdateCategoryForm (@PathVariable("id") long id, Model model){
Category category = service.findAllById(id);
model.addAttribute("category", category);
return "editCategory";
}
@PostMapping("/updateCategory/{id}")
public String updateFixtures ( @PathVariable("id") long id, @Valid Category category,
BindingResult result, Model model){
if (result.hasErrors()) {
category.setId((int) id);
return "editFixtures";
}
service.save(category);
model.addAttribute("category", service.findAll());
return "redirect:/category";
}
@GetMapping("/deleteCategory/{id}")
public String deleteCategory(@PathVariable("id") long id, Model model) {
Category category = categoryRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
categoryRepository.delete(category);
model.addAttribute("category", categoryRepository.findAll());
return "redirect:/category";
}
}
产品控制器
@Slf4j
@Controller
public class ProductController implements Serializable {
private ProductRepository productRepository;
public ProductController(ProductRepository productRepository) {
this.productRepository = productRepository;
};
@Autowired
ProductRepository service;
@Autowired
private UserRepository userRepository;
@GetMapping("/products")
public String displayCategory(Model model) {
model.addAttribute("product", service.findAll());
return "/product";
}
@GetMapping("/addProduct")
public String showSignUpForm(SessionStatus sessionStatus,
@AuthenticationPrincipal User user, Product product, Model
model) {
model.addAttribute("category",service.findAll());
return "addProduct";
}
@PostMapping("/addProduct")
public String processOrder(@Valid Product product, BindingResult result, SessionStatus
sessionStatus, Model model) {
if (result.hasErrors()) {
return "addProduct";
}
//category.setUser(user);
service.save(product);
model.addAttribute("product", service.findAll());
return "product";
}
}
类别模型
@Data
@Entity
@Table(name = "product_categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "product_category_id")
private long id;
@Column(name = "category_name")
private String name;
@Column(name = "category_description")
private String desc;
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
产品型号
@Data
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "product_id")
private long id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "product_id", referencedColumnName = "product_category_id")
public Category category;
@Column(name = "product_name")
private String name;
@Column(name = "producy_description")
private String desc;
@Column(name = "producy_quanitity")
private int quantity;
@Column(name = "producy_price")
private double price;
}
}
添加产品 HTML
<h1> Add your Products Here</h1>
<form method="POST" th:action="@{/addProduct}" class="form-
container" id="aboutForm">
<div class="form-group col-md-8">
<label class="col-form-label">Category </label>
<select id="category" name="category" th:field="*{category.id}" >
<option th:each="category : ${category}" th:value="${category.id}"
th:utext="${category.name}"/>
</select>
</div>
</form>
HTML 出错
Bean property 'id' is not readable or has an invalid getter
method:
Does the return type of the getter match the parameter type
【问题讨论】:
-
您可以在此问题的一些答案中看到 Thymeleaf 下拉列表的示例:How do I populate a drop down with a list using thymeleaf and spring。这应该为您指明正确的方向。
-
我已经尝试过了,但他们的方法似乎不起作用。
-
您能否编辑您的问题以显示您尝试过的内容、描述结果并显示任何错误消息?
-
已添加。我还添加了访问“/addProducts”页面时收到的错误消息。
-
除非您想在下拉列表的 HTML 中硬编码项目列表,否则您需要传入一个列表供 Thymeleaf 进行迭代。定义迭代器时,需要为迭代变量指定与列表变量不同的名称。所以,这是不合适的:
th:each="category : ${category}"。通常,您会有一个名为${categories}的列表,然后将每个项目称为th:each="category : ${categories}",现在您有一个${category}对象 - 并且将有一个id供您访问(使用有效的getter!)。
标签: java mysql spring jpa thymeleaf