我有一个页面,可以在其中获取条目列表。现在,我希望能够从这些列表中进行搜索。
我当前用于检索列表的网址是/show/products。我想在此页面中添加一个搜索表单,以便我可以使用请求参数进行搜索。 是的,我可以使用ajax,但我必须使用请求参数来完成。
因此,如果我搜索产品名称,则 -/show/products?name=someName
<form ui-jp="parsley" th:action="@{/show/products(name=${pName})}" th:object="${pName}" method="get">
<div class="row m-b">
<div class="col-sm-6">
Search by Name:
<input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
<button class="md-btn md-fab m-b-sm indigo">
<i class="material-icons md-24"></i>
</button>
</div>
</div>
</form>
这是我在 Controller 中尝试的:
@GetMapping("/show/products")
public String getProduct(Model model,
@RequestParam(required = false) String name,
@ModelAttribute String pName) {
List<Product> products = this.productService.getAllProducts(name)
model.addAttribute("products", products);
return "show_product";
}
我收到此错误:
Neither BindingResult nor plain target object for bean name 'pName' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:897)
最佳答案
您正在尝试使用变量 pName(模型属性)作为表单对象。
在您看来,您正在将模型属性传递给表单,如下所示 th:object="${pName}"
但您需要传递一个表单对象。
表单对象不是一个类,而是一个简单的 Java 对象 (POJO)。您可以将表单对象视为您的表单,但位于服务器端。
在 View 中使用表单对象之前,您需要创建它并将其添加到模型中。
你将这样定义它
public class MyFormObject{
private String pName;
public String getPName(){
return pName;
}
public void setPName(String pName){
this.pName = pName;
}
}
现在你的 Controller 方法将变成
@GetMapping("/show/products")
public String getProduct(Model model,
@ModelAttribute("myFormObject") MyFormObject myFormObject,
BindingResult result) {
List<Product> products = this.productService.getAllProducts(myFormObject.getPName());
model.addAttribute("products", products);
return "show_product";
}
然后你可以像这样将表单对象传递给你的表单
<form ui-jp="parsley" th:action="@{/show/products}" th:object="${myFormObject}" method="get">
<div class="row m-b">
<div class="col-sm-6">
Search by Name: <input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
<button class="md-btn md-fab m-b-sm indigo"><i class="material-icons md-24"></i></button>
</div>
</div>
</form>
您需要阅读文档,所有这些都有详细解释。
关于java - 使用 thymeleaf 中的搜索功能和请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681122/