我在使用 Thymeleaf 和 Spring-MVC 处理表单时遇到问题。这是我的看法:
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container" id="containerFragment" th:fragment="containerFragment">
<form
action="#"
th:action="@{/search}"
th:object="${searchInfo}"
method="post" >
<fieldset id="search-query">
<input
type="text"
name="search"
value=""
id="search"
placeholder="Search for user"
required="required"
th:value="*{searchQuery}" />
<input
type="submit"
value="Search"
name="submit"
class="submit"/>
</fieldset>
</form>
</div>
</body>
</html>
这是我的控制器:
/** Search form */
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(Model model) {
model.addAttribute("searchInfo", new SearchForm());
return "search";
}
/** Search form */
@RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView search(BindingResult result,
@Valid @ModelAttribute("searchInfo") SearchForm searchForm) {
String login = searchForm.getSearchQuery();
User user = userService.findUserByLogin(login);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("search-results");
modelAndView.addObject("user", user);
return modelAndView;
}
搜索表格是:
public class SearchForm {
String searchQuery;
public String getSearchQuery() {
return searchQuery;
}
public void setSearchQuery(String searchQuery) {
this.searchQuery = searchQuery;
}
@Override
public String toString() {
return "SearchForm [searchQuery=" + searchQuery + "]";
}
}
问题是在控制器的这一点登录为空:
String login = searchForm.getSearchQuery();
它看起来像是为 POST 方法创建的一个新 SearchForm 对象,但已经有一个,它是在 GET 步骤创建的,应该包含搜索查询。我无法理解这种行为。