How can i add data to th:action form

Tags: , , , ,



I have a spring-boot application. Full url that I need: localhost:8080/company/{companyName}/users?name={name}. In the beginning i choose company, for ex. : localhost:8080/company/google. The controller redirects me to the page with the form (company.html), where i type name. Controller:

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

In Data class i simply store company and name;

My form, where i type name:

<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>

So after i submit, the result url is localhost:8080/users?name=Example, i need localhost:8080/company/google/users?name=Example. How can i change it? I tried th:action=”@{/${data.company}/users}”, but ${data.company} interprets literally

Answer

Why do you want to use path and query parameters together? You can do it using either only path parameters or only query parameters.

As an answer to your question, you can try this:

<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>

Another option:

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

There are several ways to send your request to controller correctly.

  1. Send with query parameters:
    <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>

which will be the output: ‘…./service?company=google&name=david’

  1. Use th:ref attribute:
    <a th:href="@{...}">
      <span>Submit</span>
    </a>
  1. Put values inside the form and make a POST request.


Source: stackoverflow