我正在學習 Spring Boot。我有一個具有唯一 id 的產品串列,我想實作“按 id 查找”功能,但我不知道該怎么做,我進行了搜索,但得到了完全不同的東西。
我已經有一個這樣的@Getmapping 方法:
@Getmapping(/products/{id})
如果我在 url 中手動輸入 id,我會得到我想要的。但我想在 HTML 頁面中有一個輸入框,例如:
<form>
Look up by id: <input/>
</form>
在我提交表單后,它會重定向到該頁面。例如,如果我輸入 1,它將轉到 localhost:8080/products/1
我一直在搜索,但我得到的只是關于@Postmapping 的東西。
uj5u.com熱心網友回復:
下面的簡單代碼將引導您到一個 URL,該 URL 是由<form>的action屬性的基地址和它的第一個值的串聯生成的<input>:
document.querySelector("form").addEventListener("submit",function(ev){
ev.preventDefault();
this.action="/product/" this.querySelector("input").value;
console.log(this.action);
// in real code: uncomment next line!
// this.submit()
})
<form>
Look up by id: <input type="text" value="123" />
</form>
在實際代碼中,您將洗掉并console.log()取消注釋以下行:this.submit().
或者你也可以這樣做:
document.querySelector("form").addEventListener("submit",function(ev){
ev.preventDefault();
location = "/product/" this.querySelector("input").value;
})
這會將您重定向到頁面,而無需實際提交表單。
uj5u.com熱心網友回復:
將 a 添加@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 處理表單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337287.html
