【问题标题】:Spring Exception evaluating SpringEL expressionSpring Exception 评估 SpringEL 表达式
【发布时间】:2020-05-16 04:41:50
【问题描述】:

我的项目卡住了,我在我网站的另一个页面上有一个看似相同的设置,但我无法让这个工作。

DemoApplication.java

@GetMapping("/generate")
    public String GenerateForm(Model model) {
      model.addAttribute("RecipeGenerator", new RecipeGenerator());
          return "generate";
    }
    @PostMapping("/generate")
    public String GenerateSubmit(@ModelAttribute RecipeGenerator recipegenerator) throws IOException {
        recipegenerator.execute();
        System.out.println(recipegenerator.getContent());
        return "generate_result";   
    }

在这里我可以从我的方法 recipegenerator.execute 中获取任何值,但它在我的 html 页面 generate_result 上不可见,我收到此错误:

出现意外错误(类型=内部服务器错误,状态=500)。 评估 SpringEL 表达式的异常:“recipegenerator.content”(模板:“generate_result” - 第 11 行,第 10 列)

我的 HTML,生成结果:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Recipes</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<p><b><a th:text="${recipegenerator.content}" ></a></b></p>

</body>
</html>

【问题讨论】:

  • 在模型中,属性名称是RecipeGenerator(大写字母R)。但是在 html&lt;p&gt;&lt;b&gt;&lt;a th:text="${recipegenerator.content}" &gt;&lt;/a&gt;&lt;/b&gt;&lt;/p&gt; 中,情况就不同了。这可能是个问题
  • 实际上是recipeGenerator。您可以使用@ModelAttribute(name = "whatever") 来决定属性的名称。
  • 谢谢,当使用recipeGenerator 时它可以工作......但我仍然不明白为什么,它不应该是RecipeGenerator 吗? recipeGenerator 没有在任何地方提到...

标签: java html spring thymeleaf


【解决方案1】:

欢迎来到 SO。

您的相应视图需要访问该对象。因此,在您使用@PostMapping 映射的方法中,您需要/想要:

@PostMapping("/generate")
public String generateSubmit(@ModelAttribute RecipeGenerator recipeGenerator, Model model) throws IOException { //add model param
    recipeGenerator.execute();
    model.addAttribute("content", recipeGenerator.getContent()); //need this and assumes it would return a value
    System.out.println(recipeGenerator.getContent()); //use a logger if you can instead
    return "generate_result";   
}

然后在你的 HTML 中:

&lt;p&gt;&lt;strong&gt;&lt;a th:text="${content}"&gt;[Some Link]&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

还有:

我强烈推荐 Java 风格的驼峰式大小写约定以保持一致性,因为下一个程序员阅读和实现您的代码可能会在区分大小写方面产生错误。所以,recipeGenerator 是有意义的,当然除了类名。

请注意,&lt;b&gt; 标记已弃用。

在链接中包含占位符文本,因为您可以在浏览器上打开 HTML 页面而不提供它并查看 UI 的呈现方式。

确保发布完整的堆栈跟踪。如果您在跟踪中向下滚动,您会发现更多有用的信息。

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多