【问题标题】:How can i add data to th:action form如何将数据添加到 th:action 表单
【发布时间】:2020-09-04 18:31:24
【问题描述】:

我有一个 spring-boot 应用程序。 我需要的完整网址:localhost:8080/company/{companyName}/users?name={name}。 一开始我选择公司,例如。 :本地主机:8080/公司/谷歌。控制器将我重定向到表单 (company.html) 的页面,我在其中键入名称。 控制器:

@GetMapping("/company/{company}")
    public String greetingForm(@PathVariable String company, Model model) {
        Data data = new Data();
        data.setCompany(company);
        model.addAttribute("data", data);
        return "company";
    }

在数据类中,我只存储公司和名称;

我的表单,我在其中输入名称:

<form action="#" th:action="@{/users}" th:object="${data}" method="get">
    <p>Name: <input type="text" th:field="*{name}" /></p>
    <p><input type="text" th:value="${data.company}"></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>

所以我提交后,结果 url 是 localhost:8080/users?name=Example,我需要 localhost:8080/company/google/users?name=Example。我怎样才能改变它?我试过 th:action="@{/${data.company}/users}",但 ${data.company} 是字面意思

【问题讨论】:

  • 请出示您的@PostMapping方法

标签: java html spring spring-boot web


【解决方案1】:

为什么要同时使用路径和查询参数?您可以只使用路径参数或只使用查询参数。

作为您问题的答案,您可以试试这个:

<form th:action="@{/company/{id}/users(id=${company.name})}" method="get">
  <input type="hidden" name="name" th:value="${user.name}">
  <input type="submit" value="Submit" />
</form>

另一种选择:

<form th:action="@{/company/{id}/users(id=${company.name},name=${user.name})}" method="get">
  <input type="submit" value="Submit" />
</form>

有几种方法可以正确地将您的请求发送到控制器。

  1. 使用查询参数发送:
    <form th:action="@{/service}" method="get">
      <input type="text" name="company" th:value="${company.name}" />
      <input type="text" name="name" th:value="${user.name}" />
      <button type="submit">Submit</button>
    </form>

这将是输出:'..../service?company=google&name=david'

  1. 使用 th:ref 属性:
    <a th:href="@{...}">
      <span>Submit</span>
    </a>
  1. 将值放入表单并发出 POST 请求。

【讨论】:

  • 为什么要同时使用路径和查询参数? -> 这就是任务需要的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-01-16
  • 2021-01-10
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
相关资源
最近更新 更多