首页 > 解决方案 > Thymleaf 如何接受输入然后重定向到另一个页面

问题描述

我正在学习Spring Boot。我有一个具有唯一 id 的产品列表,我想实现“按 id 查找”功能,但我不知道该怎么做,我搜索但得到了完全不同的东西。

我已经有一个像这样的@Getmapping 方法:

@Getmapping(/products/{id})

如果我在 url 中手动输入 id,我会得到我想要的。但我想在 HTML 页面中有一个输入框,例如:

<form>
   Look up by id: <input/>
</form>

在我提交表单后,它会重定向到该页面。例如,如果我输入 1,它将转到 localhost:8080/products/1

我一直在搜索,但我得到的只是关于@Postmapping 的东西。

标签: htmlspring-bootthymeleafrequest-mapping

解决方案


添加一个@PostMapping到你的控制器:

@Controller
@RequestMapping("/products")
public class ProductController {

  @GetMapping //Controller method for showing the empty form
  public String index(Model model) {
    model.addAttribute("formData", new SearchFormData()); // Create an empty form data object so Thymeleaf can bind to it

    return "index";
  }

  @PostMapping
  public String searchById(SearchFormData formData) {
    return "redirect:/products/" + formData.getId(); //Use the value the user entered in the form to do the redirect
  }

  @GetMapping("/{id}")
  public String showProduct(@PathVariable("id") long id) {
    ...
  }
}

SearchFormData表示表单字段(在这种情况下只有 1 个字段):

public class SearchFormData {
  private long id;

  // getters and setters

并像这样更新 Thymeleaf 模板:

<form th:action="@{/products}" th:method="post" th:object="${formData}">
  <input th:field="*{id}" type="number">
  <button type="submit">Search</button>
</form>

请注意, 的值th:object需要与用于将SearchFormData实例添加到模型的名称相匹配。

有关更多信息,请参阅使用 Thymeleaf 处理表单


推荐阅读