0

我对如何配置控制器以通过表单更改变量有疑问。我目前正在使用 Thymeleaf 进行模板化,并且我按照 Spring 文档设置了我的控制器。

现在,每当发出请求时,我的控制器都会成功创建类“Bill”的新实例......

@Controller
public class BudgetController {

@Autowired
private BillBook book;

@GetMapping("/")
public String billForm(ModelMap modelMap, Model model) {
    model.addAttribute("bill", new Bill());
    modelMap.put("billName", name);
    return "home";
}

@PostMapping("/")
public String billSubmit(Model model, @ModelAttribute Bill bill) {
      book.addToBillBook(bill);
      return "redirect:/";
}

}

...并将其传递到“BillBook”类的列表中。

@Component
public class BillBook {
private List<Bill> billList;
private int paycheckTotal;
private int difference;
private int billTotal;


public BillBook() {
    billList = new ArrayList<>();
    paycheckTotal = 0;
    difference = 0;
    billTotal = 0;
}

public void addToBillBook(Bill bill) {
    billList.add(bill);
}

public void setPaycheckTotal(int amount) {
    paycheckTotal = amount;
}

public int getPaycheckTotal () {
    return paycheckTotal;
}

每次用户将账单名称输入到我在 Thymeleaf 中构建的表单时都会执行此操作。

<h1>Form</h1>

<form action="#" th:action="@{/}" th:object="${bill}" method="post">
    <p>Bill name <input type="text" th:field="*{name}" /></p>
    <p>Bill amount <input type="text" th:field="*{amount}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" 
    value="Reset"/></p>
</form>

我知道我仍然需要进行一些更改,以便将金额也包括在内,但现在效果还不错。

但是,我现在要做的是允许用户在表单中输入薪水金额,该金额应存储在 BillBook 类的“paycheckTotal”变量中。我希望这是一个常数——即,用户只能提交一张薪水,每次他们输入新的薪水时,它都会覆盖之前的薪水。

根据我的研究,我认为这应该通过 @RequestParam 注释来完成。大概是这样的吧?

public String billSubmit(Model model, @ModelAttribute Bill bill, 
@RequestParam ("paycheckTotal") int paycheckTotal) {

但我不确定如何在 Thymeleaf 模板中构造它,以便将其存储在 paycheckTotal 变量中。

如果有人能告诉我应该如何构建它,那将非常非常感激。

4

1 回答 1

0
<form action="#" th:action="@{/}" th:object="${bill}" method="post">
    <p>Bill name <input type="text" th:field="*{name}" /></p>
    <p>Bill amount <input type="text" th:field="*{amount}" /></p>
    <p>Paycheck total <input type="text" th:value="${paycheckTotal}" th:name="paycheckTotal"/></p>
    <p><input type="submit" value="Submit" /> <input type="reset" 
    value="Reset"/></p>
</form>

如果需要默认值,还可以添加:

model.addAttribute("paycheckTotal", paycheckTotal);
于 2018-10-12T14:08:41.183 回答