Thymeleaf跳转new.html出现模板解析错误的问题如何解决
错误原因
- 核心原因1:
new.html存在HTML标签不匹配问题,代码中使用了<tr>、<td>、</table>表格相关标签,但没有对应的<table>起始标签,Thymeleaf对模板语法校验严格,标签不配对直接触发解析失败。 - 核心原因2:
new.html中多处属性名拼写错误,把align错写为alight,属于无效属性会影响布局。 - 次要原因:Controller的编辑接口
showEditStudentPage向模板传递的属性名为student,但new.html中th:object绑定的是${client},后续访问编辑页面时也会触发属性找不到的解析错误。
修复方案
1. 修正new.html代码
替换你的new.html为以下内容,补全表格标签、修正属性拼写:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>Create New Client</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/cosmo/bootstrap.min.css" /> <script src= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" ></script> </head> <body> <div align="center"> <h1>Create New Client</h1> <br /> <div class="col-sm-4"> <form action="#" th:action="@{/save}" th:object="${client}" method="post"> <!-- 补全table起始标签 --> <table> <div align="left"> <tr> <label class="form-label" >Client Name</label> <td> <input type="hidden" th:field="*{id}" /> <input type="text" th:field="*{clientname}" class="form-control" placeholder="Client Name" /> </td> </tr> </div> <div align="left"> <tr> <label class="form-label" >Hookah</label> <td><input type="text" th:field="*{hookah}" class="form-control" placeholder="Hookah" /></td> </tr> </div> <div align="left"> <tr> <label class="form-label" >Fee</label> <td><input type="text" th:field="*{fee}" class="form-control" placeholder="Fee" /></td> </tr> </div> <br> <tr> <td colspan="2"><button type="submit" class="btn btn-info">Save</button> </td> </tr> </table> </form> </div> </body> </html>
2. 修正Controller编辑接口属性名
找到showEditStudentPage方法,修改属性名和模板匹配:
@RequestMapping("/edit/{id}") public ModelAndView showEditStudentPage(@PathVariable(name = "id") int id) { ModelAndView mav = new ModelAndView("new"); Client std = service.get(id); // 把student改成client,和模板的th:object保持一致 mav.addObject("client", std); return mav; }
3. 验证修复效果
重启项目后点击首页的新增按钮,即可正常跳转到new.html页面,编辑功能也可正常使用。
内容的提问来源于stack exchange,提问作者BurningChuck
相关产品推荐
相关产品推荐

