【问题标题】:How pass extra param from html to controller如何将额外的参数从 html 传递到控制器
【发布时间】:2020-04-19 15:33:55
【问题描述】:

Spring Boot 2.5,Thymeleaf

点击提交时我需要传递对象产品和额外的额外参数(数量)

html模板:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${appName}">Category template title</title>
    <link th:href="@{/public/style.css}" rel="stylesheet"/>
    <meta charset="UTF-8"/>
</head>
<body>
<div class="container">
    <h3 th:text="*{title}"/>
    <form method="post" action="#" th:object="${product}" th:action="@{/product}">
        <input type="hidden" id="id" th:field="*{id}"/>
        <input type="text" placeholder="Name" id="name" th:field="*{name}" th:disabled="${isView}"/>
        <input type="hidden" id="created" th:field="*{created}"/>
        <textarea placeholder="Description" rows="5" id="description"
                  th:field="*{description}" th:disabled="${isView}"></textarea>
        <input type="number" placeholder="Price" id="price" th:field="*{price}" th:disabled="${isView}"/>
        <input type="text" placeholder="Currency" id="currency" th:field="*{currency}" th:disabled="${isView}"/>
        <input type="text" placeholder="Images URL(separate by comma)" id="images" th:field="*{images}" th:disabled="${isView}"/>
        <input th:type="${isView} ? hidden : submit" value="Submit"/>
    </form>
</div>
</body>
</html>

这里是我的控制器:

 @RequestMapping("cart/add")
    public String addProduct(Model model) {
        logger.info("addProduct");
        model.addAttribute("isAdd", true);
        model.addAttribute("product", new Product());
        model.addAttribute("title", "Add Product");
        model.addAttribute("viewMode", ViewMode.ADD);
        return "product";
    }

    @PostMapping(value = "/product")
    public String submitProduct(Product product, Model model) {
        logger.info("submitProduct = " + product);
        if (product.getId() == 0) { // add category
            product.setCreated(new Date());
        } else { // update category
            product.setUpdated(new Date());
        }
        return "redirect:/cart";
    }

所以当点击按钮提交调用submitProduct 填充对象产品。但我需要传递额外的参数(作为方法submitProduct 中的第二个参数) - 数量。 如何将这个额外的 int 参数从 html 传递给控制器​​?

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    一种选择是直接从请求参数中访问值。

    假设数量值在表单中作为输入字段可用,名称为quantity(目前看起来在那里),那么您可以将控制器更改为使用这个:

    import org.springframework.web.bind.annotation.RequestParam;
    

    然后把相关的方法签名改成这样:

    public String submitProduct(Product product, Model model,
            @RequestParam(name = "quantity") String quantity) {...}
    

    (我认为还需要某种字段验证。)

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      相关资源
      最近更新 更多