[英]How to solve thymeleaf template parsing error
我正在尝试向屏幕显示 html,但我从 thymeleaf 收到模板解析器错误。这是我的代码和错误:
索引.html:
<body>
<h2>My ToDo List</h2>
<form action="/send-form-data" method="post" th:object="${myForm}">
<table>
<tr>
<td>Title:</td>
<td><input type="text" th:field="*{title}"/></td>
</tr>
<tr>
<td>Decription:</td>
<td><input type="text" th:field="*{description}"/></td>
</tr>
</table>
controller:
@Controller public class TodolistController { @RequestMapping(value = { "/display-form", "/index.html" }, method = RequestMethod.GET) public ModelAndView displayForm() { ModelAndView mv = new ModelAndView("index"); mv.addObject("myForm", new MyModel()); return mv; }
}
我的模型:
public class MyModel { private String title; private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
}
错误:
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 15, col 28) Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'formData' available as request attribute
我尝试了一些但没有帮助。 当我从 HTML 中删除输入时,它工作正常,所以问题是关于将 thymeleaf 字段与 MyModel 变量匹配,但我无法解决。
我试过你的程序,我认为你在浏览器中输入了错误的 url。 因为你的代码没有错。
根据您的 controller:
@RequestMapping(value = { "/display-form", "/index.html" }, method = RequestMethod.GET)
请确保您的浏览器的 url 是:
<host>:<port>/<context-path>/index.html
或<host>:<port>/<context-path>/display-form
而不是<host>:<port>/<context-path>/
。
问题是, <host>:<port>/<context-path>/
是默认的欢迎页面,而 Spring 直接呈现您的index.html
而不通过您的 Controller。这就是为什么您会遇到带有 BindingResult 问题的 IllegalStateException。
但是,如果您输入了正确的 url 路径,那么您将看到预期的页面:
仅根据错误消息,我会假设您要填写的目标 object 丢失,或者您当前提供它的方式不起作用。 您可以将 controller 方法调整为
@Controller
public class TodolistController {
@RequestMapping(value = { "/display-form", "/index.html" }, method = RequestMethod.GET)
public String displayForm(Model model) {
model.addAttribute("myForm", new MyModel());
return "index";
}
假设您的 index.html 位于资源/模板中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.