Thymleaf如何接受输入,然后重定向到另一个页面



我正在学习Spring引导。我有一个带有唯一id的产品列表,我想实现一个";按id查找";功能,但我不知道怎么做,我搜索了一下,但得到了完全不同的东西。

我已经有了这样的@Getmapping方法:

@Getmapping(/products/{id})

如果我手动在url中键入id,我会得到what I what。但我想在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

并更新Thymelaf模板如下:

<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实例添加到模型中的名称相匹配。

有关更多信息,请参阅百里香的表格处理。

下面的简单代码将引导您找到一个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;
})

这会将您重定向到页面,而无需实际提交表单。

最新更新