【问题标题】:How to read the attributes set in model in Thymeleaf如何在 Thymeleaf 中读取模型中设置的属性
【发布时间】:2020-02-26 18:59:52
【问题描述】:

我正在尝试使用 spring boot thymeleaf 从模型中读取属性。

@GetMapping("/summary")
public String getSummaryScreen(Model model) {       
    Application application= getApplicationData();
    ClientValidationModel clientValidationModelView = getclientModel();
    model.addAttribute("clientValidationModelView",clientValidationModelView);
    model.addAttribute("application",application);
    return "summary";
}
class application{
   private int applicationNumber;
   private string name;

   ... getter & setter
}

在 Thymeleaf 中,我正在尝试读取应用程序值

<div th:text ="${application.applicationNumber}"></div>

从下面的评论中删除空格后,这是我在浏览器上看到的 org.thymeleaf.context.WebEngineContext$ServletContextAttributesMap@7e8999c3。我希望然后显示应用程序编号

更新

我注意到 thymeleaf 没有解析 java 对象。即使我尝试

@GetMapping("/summary")
public String getSummaryScreen(Model model) {       
   Application application= getApplicationData();
   ClientValidationModel clientValidationModelView = getclientModel();       
    model.addAttribute("clientValidationModelView",clientValidationModelView);
   model.addAttribute("application","This my application");
   return "summary";
}

在 HTML 上只能获取 "org.thymeleaf.context.WebEngineContext$ServletContextAttributesMap@1f6b5bcf"

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    你正确使用了变量表达式,你能不能确保两者之间没有空格:

    <div th:text="${application}"></div>
    

    您正在尝试读取 summary.html 中的 application 属性,对吗?

    另外,您能否尝试以下方法进行测试:

    model.addAttribute("application", "test to see if the variable expression works");
    

    【讨论】:

    • 谢谢,是的,我使用了正确的 html 文件并且没有空间。我通过 maven 构建项目,它工作(我认为 spring boot 重启应该工作。)但现在我有另一个问题,我无法访问类变量。编辑问题
    • 你写的在我看来也是正确的。请确保中间没有空格: th:text="${application.applicationNumber}"> 如果不起作用,请将变量 applicationNumber 导出到自己的模型属性中进行测试: model.addAttribute("applicationNumber", application.getApplicationNumber());
    • 那么请尝试我的其他建议。此外,你的 getter 应该这样命名:getApplicationNumber(),以便 Thymeleaf 通过变量名识别它。
    • 我累了 model.addAttribute("applicationNumber",application.getApplicationNumber());但在 html
      上显示为 org.thymeleaf.context.WebEngineContext$ServletContextAttributesMap@7e8999c3
    • 实际上我的应用程序类真的很大,有很多嵌套类,问题是由于任何内存溢出之类的东西
    【解决方案2】:

    经过一番思考,我发现问题出在我用来设置模型属性的变量名“applicaiton”上。我可以通过将属性名称设置为“newapplication”来解决这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 2019-08-07
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多