我创建了一个页面,使用spring boot& amp; thymeleaf。在我的SearchStudent.html
页面中,有3个字段作为搜索参数(firstName,lastName,city)。我的要求是,即使我没有输入参数(全部搜索)或基于参数,搜索也应该有效。 '全部搜索'条件工作但不确定如何在搜索条件中传递部分或全部参数时更改控制器。
SearchController
@Controller
@ComponentScan
public class SearchController {
@Autowired
protected StudentRepository repository;
@RequestMapping(value = {"/","/search"}, method = RequestMethod.GET)
public String search(Model model) {
model.addAttribute("student", new Student());
model.addAttribute("allStudents", (ArrayList<Student>)repository.findAll());
return "SearchStudent";
}
SearchStudent.html
<div class="panel-body">
<form th:object="${student}" th:action="@{/search}" action="#" method="get">
<input type="text" th:field="*{firstName}" class="form-control" placeholder="First Name" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="text" th:field="*{lastName}" class="form-control" placeholder="Last Name" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="text" th:field="*{city}" class="form-control" placeholder="City" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="submit" class="btn btn-danger pull-right" value="Search">
<input type="submit" class="btn btn-success pull-right" value="Clear">
</form>
</div>
答案 0 :(得分:1)
您的表单将表单字段绑定到th:object $ {student},它是控制器需要实现的HTTP POST方法的输入参数。它应该是这样的:
@RequestMapping(method=RequestMethod.POST, value="/search")
public ModelAndView doSearch(Student student){
// do your conditional logic in here to check if form parameters were populated or not
// then do something about getting results from the repository
List<String> students = repository.find....;
// return a model and a view (just as an example)
ModelAndView mv = new ModelAndView();
mv.addObject(students);
mv.setViewName("/results");
return mv;
}
您还应该将表单的方法设置为“发布”
<form th:object="${student}" th:action="@{/search}" action="#" method="post">
提交带有输入字段数据的表单,以便将其放入模型中并通过HTTP POST发送,请参见此处:http://www.w3schools.com/tags/att_form_method.asp
或者,您可以添加第二个不同的GET请求映射,该映射用于解析URL参数中的表单字段。将表单方法保留为“get”,您将添加另一个GET请求映射,如下所示:
@RequestMapping(value = {"/search"}, method = RequestMethod.GET)
public String doSearch(@PathVariable String firstName, @PathVariable String lastName, @PathVariable String city) {
// Add your conditional logic to search JPA repository based on @PathVariable values delivered from form submission using HTTP GET
List<String> students = repository.find....;
ModelAndView mv = new ModelAndView();
mv.addObject(students);
mv.setViewName("/results");
return mv;
}
但请注意使用form method ='get'发送表单数据的限制和安全隐患。