从处理表单提交指南中获取代码错误(Spring入门指南)

时间:2019-01-10 03:41:37

标签: java spring thymeleaf

我正在遵循this入门指南和以下错误:

org.thymeleaf.exceptions.TemplateProcessingException:执行处理器'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor'时出错(模板:“索引”-第10行,第31行)“

代码与指南中显示的完全相同。我知道这与Thymeleaf表单标签有关,因此我也检查了Thymeleaf documentation,但无法弄清楚我的代码出了什么问题。

代码如下:

index.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
  <h1>Form</h1>
  <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
    <p>Id: <input type="text" th:field="*{id}" /></p>
    <p>Message: <input type="text" th:field="*{content}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
  </form>
</body>
</html>

GreetingController.java

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greetingForm(Model model) {
        model.addAttribute("greeting", new Greeting());
        return "greeting";
    }

    @PostMapping("/greeting")
    public String greetingSubmit(@ModelAttribute Greeting greeting) {
        return "result";
    }
}

Greeting.java

package com.example;

public class Greeting {

    private long id;
    private String content;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

我将不胜感激。

1 个答案:

答案 0 :(得分:0)

因此,本教程要求您创建两个文件result.htmlgreeting.html。然后您创建了index.html。问题是您没有将模板页面绑定到Spring控制器,而是像教程中那样绑定到greeting.html

因此解决方案只是将greetingForm()方法中的收益从 greeting 更改为 index

@GetMapping("/greeting")
public String greetingForm(Model model) {
    model.addAttribute("greeting", new Greeting());
    return "index"; // <- changed line
}

希望这会对您有所帮助。