我有一个页面,可以在其中获取条目列表。现在,我希望能够从这些列表中进行搜索。
我当前用于检索列表的网址是/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>
这是我在控制器中尝试的:
@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)。您可以将表单对象视为您的表单,但位于服务器端。
在视图中使用表单对象之前,您需要创建它并将其添加到模型中。
你会这样定义它
public class MyFormObject{
private String pName;
public String getPName(){
return pName;
}
public void setPName(String pName){
this.pName = pName;
}
}
现在你的控制器方法将变成
@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>
您需要阅读文档,所有这些都有详细解释。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)