我正在开发一个 Web 应用程序,使用 Spring MVC 和 Thymeleaf 作为我的 ViewResolver。我有以下 Controller 处理程序方法:
@RequestMapping(value = "/something", method = RequestMethod.POST, params = "submit")
public String doSomething(@ModelAttribute("error") String error /*, other attributes */) {
// find out if there is an error
error = getErrorMessage();
return "someHTMLfile";
}
我的 View 包含这一行:
<p><span th:text="${error}">Error Message goes here</span></p>
执行时,该标记不会呈现任何内容。这可能是由于 ${error}
评估为空字符串,但我不明白为什么。 Spring 的 @ModelAttribute
注解不会自动将对象添加到模型映射中,Thymeleaf 可以在其中找到它吗?
如果我有:
@RequestMapping(value = "/something", method = RequestMethod.POST, params = "submit")
public String doSomething(ModelMap map /*, other attributes */) {
// find out if there is an error
String error;
error = getErrorMessage();
map.addAttribute("error", error);
return "someHTMLfile";
}
View 渲染得非常好,并带有错误消息。 @ModelAttribute 是否未将对象添加到请求模型中?
编辑:我尝试过同时执行以下操作:
@RequestMapping(value = "/something", method = RequestMethod.POST, params = "submit")
public String doSomething(@ModelAttribute("error") String error, ModelMap map /*, other attributes */) {
// find out if there is an error
error = getErrorMessage();
map.addAttribute("error", error);
return "someHTMLfile";
}
这也行不通。
最佳答案
实际上,我认为您的问题与 Thymeleaf 无关,而与 SpringMVC 相关:-)
在第一个代码片段中,您没有向请求模型添加任何内容,而是尝试从表单返回一个名为“error”的对象。
在第二个代码片段中,您确实向模型添加了一个对象,这就是您的 View 渲染良好的原因。
看看SpringMVC doc here (16.3.3.8) 更好地理解方法参数上的 @ModelAttribute 注释。
关于java - Spring MVC 和 thymeleaf ModelAttribute 为 null 或未评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14179972/