如何将数据添加到操作表单



我有一个弹簧启动应用程序。 我需要的完整网址:localhost:8080/company/{companyName}/users?name={name}。 一开始我选择公司,例如:localhost:8080/company/google。控制器将我重定向到带有表单(公司.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>

所以在我提交后,结果网址是localhost:8080/users?name=Example,我需要localhost:8080/company/google/users?name=Example。如何更改它?我尝试了th:action="@{/${data.company}/users}",但是${data.company}从字面上解释

为什么要同时使用路径和查询参数?可以仅使用路径参数或仅使用查询参数来执行此操作。

作为您问题的答案,您可以尝试以下操作:

<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 请求。

最新更新