【问题标题】:Thymeleaf form - how to pass a value for model attribute from one controller method to another oneThymeleaf 形式 - 如何将模型属性的值从一个控制器方法传递到另一个控制器方法
【发布时间】: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


    【解决方案1】:

    看到这个答案: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}" />
    

    那么你的控制器方法应该得到它。让我知道这是否有帮助。

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多