java - Spring 异常评估 SpringEL 表达式

标签 java html spring thymeleaf

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

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>

最佳答案

欢迎来到SO。

您相应的 View 需要访问该对象。所以在你的方法中映射 @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 中:

<p><strong><a th:text="${content}">[Some Link]</a></strong></p>

另外:

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

请注意<b>标签已弃用。

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

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

关于java - Spring 异常评估 SpringEL 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61822695/

相关文章:

java - Spring Batch - 作业实例已存在 : JobInstanceAlreadyCompleteException

java - 来自 Url 的 android JSON

Java:无法初始化 InetAddress

javascript - 表单提交不遵循重定向 (Node.js)

javascript - 使用 Javascript 更改样式的更有效方法?

java - 在 Spring 中的存储过程中传递参数

java - WS动态客户端和complexType参数

java - Tomcat 8 的问题

html - 图像类型下拉菜单的悬停 CSS

java - 如何在Spring中使用WebLogic 12.2.1提供的JNDI DataSource?