如何使用Post方法创建一个表单并将一个Integer值传递给控制器​​?

时间:2018-01-27 18:57:31

标签: java spring-boot thymeleaf

我想创建一个包含Number类型字段的表单,并通过POST方法将其值传递给控制器​​。

UserController.java

@GetMapping("/users/{id}")
public String showUserProfile(@PathVariable final Long id, Model model) {
    model.addAttribute("user", userService.getUserById(id));
    model.addAttribute("howMuchToIncrease", new Integer(0));
    return "user/user_item";
}

@PostMapping("/users/{id}/refill")
public String showButtonTopUpBalance(@PathVariable final Long id,
                                     @ModelAttribute("howMuchToIncrease") Integer howMuch) {
    userService.topUpBalance(id, howMuch);
    return "redirect:/users/" + id;
}

用户/ user_item.html

<form role="form" method="post" th:object="${howMuchToIncrease}"
  th:action="@{'/users/{id}/refill' (id=${user.id})}">
    <input type="number" th:field="${howMuchToIncrease}"/>
    <button type="submit">To Up Balance</button>
</form>

但是在我按下确认按钮后,这一切都以此错误结束:

  

无法实例化[java.lang.Integer]:找不到默认构造函数;嵌套异常是java.lang.NoSuchMethodException:java.lang.Integer。()   org.springframework.beans.BeanInstantiationException:无法实例化[java.lang.Integer]:找不到默认构造函数;嵌套异常是java.lang.NoSuchMethodException:java.lang.Integer。()

1 个答案:

答案 0 :(得分:1)

th:object必须引用一个bean,在你的情况下它是一个值。值不是java bean。

尝试以下方法:

予。添加bean类:

public class IncreaseData {
    private int howMuchToIncrease = 0;

    public int getHowMuchToIncrease() {
        return howMuchToIncrease;
    }

    public void setHowMuchToIncrease(int howMuchToIncrease) {
        this.howMuchToIncrease = howMuchToIncrease;
    }
}

II。使用它而不是Integer实例:

model.addAttribute("increaseData", new IncreaseData());

public String showButtonTopUpBalance(@PathVariable final Long id,
                                     @ModelAttribute("increaseData") IncreaseData howMuch) {

III。在您的模板中:

<form role="form" method="post" th:object="${increaseData}"
  th:action="@{'/users/{id}/refill' (id=${user.id})}">
    <input type="number" th:field="*{howMuchToIncrease}"/>
    <button type="submit">To Up Balance</button>
</form>

(请注意th:field中的星号)。