【发布时间】:2019-09-26 09:02:07
【问题描述】:
我正在努力将产品添加到特定用户的产品表中,这是通过 log 方法记录的。问题是属性 userLogin 失去了他的价值并且不等于登录的用户。所以addProduct方法中userLogin属性的实际值为null,所以存在异常。
@RequestMapping("/home")
public String home(Model model) {
model.addAttribute("customer", new Customer());
model.addAttribute("userLogin", new Customer());
return "register";
}
@PostMapping("/save")
public String save(@ModelAttribute(value = "customer") @Valid Customer customer, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new NotValidInputException();
}
if (customerService.checkIfCustomerIsInDb(customer)) {
throw new CustomerAlreadyExists();
}
customerService.saveCustomerIntoDb(customer);
return "saved";
}
@ExceptionHandler(NotValidInputException.class)
public String notValidInputExceptionHandler() {
return "databaseError";
}
@ExceptionHandler(CustomerAlreadyExists.class)
public String customerAlreadyInDbHandler() {
return "customerError";
}
@RequestMapping("/log")
public String login(Model model, @ModelAttribute(name = "userLogin") Customer customerFromLoginForm) {
if (Objects.isNull(customerService.getUserByLoggingDetails(customerFromLoginForm))) {
return "userNotFound";
}
model.addAttribute("product", new Product());
return "logged";
}
@PostMapping(value = "/addProduct")
public String addProduct(@ModelAttribute("userLogin") Customer customerFromLoginForm, @ModelAttribute(value = "product") Product product) {
// customer is null
customerFromLoginForm = customerService.findCustomerById(customerFromLoginForm.getId());
product.setCustomer(customerFromLoginForm);
customerFromLoginForm.setProducts(Arrays.asList(product));
productService.addProduct(product);
return "logged";
}
已登录的表单。 html
<form th:method="post" th:action="@{addProduct}" th:object="${product}">
<input type ="text" th:field="*{name}" placeholder="Name" /><br />
<input type ="text" th:field="*{category}" placeholder="Category" /><br />
<input type="number" th:field="*{price}" placeholder="Price" /><br />
<input style="text-align: center" type="submit" value="Add Product" /> </form>
不确定我在这里缺少什么
【问题讨论】:
标签: spring-boot spring-mvc logging spring-data thymeleaf