【问题标题】:Spring MVC and thymeleaf ModelAttribute either null or not evaluatedSpring MVC 和 thymeleaf ModelAttribute 为 null 或未评估
【发布时间】:2013-01-09 00:00:05
【问题描述】:

我正在开发一个使用 Spring MVC 和 Thymeleaf 作为我的 ViewResolver 的 Web 应用程序。我有以下控制器处理程序方法:

    @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";
    }

我的视图包含这一行:

<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";
}

显示错误消息的视图完美无缺。 @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";
}

这也行不通。

【问题讨论】:

    标签: java html spring-mvc thymeleaf


    【解决方案1】:

    实际上我认为您的问题与 Thymeleaf 无关,只是 SpringMVC :-)

    在您的第一个 sn-p 中,您没有向请求模型添加任何内容,而是尝试从表单中获取一个名为“error”的对象。

    在您的第二个 sn-p 中,您确实向模型添加了一个对象,这就是您的视图渲染良好的原因。

    查看SpringMVC doc here (16.3.3.8) 以更好地理解方法参数上的@ModelAttribute 注解。

    【讨论】:

    • An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model.
    • 事实证明我们都错了,ModelAttribute 确实符合我的想法。我很惭愧地说这是一个 Java 问题。看我的回答。
    【解决方案2】:

    我觉得自己很愚蠢,但无论如何,我们都会犯错。

    Spring 正在为我创建一个新的 String 实例,并将其注入到我的方法中,并注入到键 error 下的模型中。 String 是一个不可变对象,所以当我执行error = getErrorMessage() 时,我将另一个实例分配给我的error 对象。现在在 Spring 的模型中有我的error 和错误String,值为""。这就是为什么 Thymeleaf 渲染只能找到空字符串的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 2012-01-01
      • 2021-04-27
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      相关资源
      最近更新 更多