html - 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 的东西。
解决方案
添加一个@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 处理表单。
推荐阅读
- angular - Angular Upgrade 8 to 11 version Error : Class extends value undefined is not a constructor or null
- python - 使用单个原子解决 python 中的分子结构
- python - google-cloud-datacatalog 0.8.0 缺少 TagTemplate 选项
- collision-detection - 前 42 亿个 CRC32 中的碰撞概率是多少
- powershell - Powershell 脚本在本地工作,但不能在 solarwinds SAM 组件下工作
- django - CSRF 令牌丢失 - django/ajax
- r - 如何在R中的rCBA包中使用fpgrowth算法中的结果参数?
- python - 丢弃时间接近的相同 ID 的行
- set - setTitle 在 FormApp.ItemType.TEXT 没有处理表单上的 textitem 的情况下跳过一列接一列
- flutter - 提供者提供空值