Thymeleaf形式-如何将模型属性的值从一种控制器方法传递到另一种方法

时间:2019-05-08 15:15:38

标签: spring-boot spring-mvc logging spring-data thymeleaf

我正在努力将产品添加到特定用户的产品表中,这是通过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>

不确定我在这里缺少什么

1 个答案:

答案 0 :(得分:0)

查看此答案:Not able to pass model Attribute passed from controller to thymeleaf html back to another controller。 通常,我会使用隐藏的输入,例如:

<input type ="hidden" th:name="userLogin" th:value="${userLogin}" />

然后您的控制器方法应该可以得到它。让我知道是否有帮助。