SpringBoot+Thymeleaf表单传参列表渲染异常求助
解决Thymeleaf表单提交对象列表参数的异常问题
兄弟,你这问题太典型了!从你给出的错误URL(http://localhost:8080/@%7B/%7D?%24%7Bcontent%7D=hello)和Eclipse的提示来看,核心问题是Thymeleaf的表达式完全没被正确解析,直接当成纯字符串输出并提交了,导致服务器根本识别不了参数。下面给你一步步拆解解决:
错误根源分析
你肯定是在表单里犯了这两个常见错误之一:
- 表单的
action属性用了原生的action="@{/}",而不是Thymeleaf的th:action="@{/}",所以@{/}被URL编码成了@%7B/%7D; - 输入框的
name属性用了name="${content}",而不是th:name="...",导致${content}被编码成%24%7Bcontent%7D,服务器自然识别不了这个参数名。
正确实现步骤
1. 定义实体类(接收列表的对象)
首先你需要一个对应表单条目的实体类,比如:
public class ContentItem { private String content; // 必须要有无参构造器,Spring才能实例化 public ContentItem() {} // getter和setter public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
2. 编写SpringBoot控制器
控制器要能接收列表参数,并用@ModelAttribute绑定,同时处理GET请求返回表单页面,POST请求处理提交:
@Controller public class FormController { // 显示表单页面 @GetMapping("/form") public String showForm(Model model) { // 初始化一个空列表,避免Thymeleaf遍历空值报错 List<ContentItem> items = new ArrayList<>(); // 可以先加几个空条目让页面默认显示 items.add(new ContentItem()); items.add(new ContentItem()); model.addAttribute("items", items); return "form"; } // 处理表单提交 @PostMapping("/submit") public String submitForm(@ModelAttribute("items") List<ContentItem> items, Model model) { // 这里就可以遍历处理提交的条目了 for (ContentItem item : items) { System.out.println("提交的内容:" + item.getContent()); } model.addAttribute("submittedItems", items); return "result"; } }
3. 编写正确的Thymeleaf表单页面
重点注意必须用Thymeleaf的th:前缀属性,不能混用原生HTML属性:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>表单提交列表</title> </head> <body> <h1>提交内容列表</h1> <!-- 必须用th:action指定提交路径,Thymeleaf才会解析@{/submit} --> <form th:action="@{/submit}" method="post"> <!-- 用th:each遍历列表,stat是状态变量,用来获取索引 --> <div th:each="item, stat : ${items}"> <!-- 用th:name绑定参数,格式为items[索引].属性名,Spring才能识别为列表 --> <input type="text" th:name="items[__${stat.index}__].content" th:value="${item.content}" placeholder="输入内容"/> <br/> </div> <button type="submit">提交</button> </form> </body> </html>
4. 验证效果
启动项目后访问http://localhost:8080/form,输入内容提交后,控制器就能正确接收到列表参数,不会再出现错误URL和表达式无效的提示了。
额外注意事项
- 实体类必须有无参构造器,否则Spring无法实例化对象;
- 遍历列表时,状态变量
stat的index要放在__${}__里,Thymeleaf才会正确解析索引值; - 不要混用原生HTML属性和Thymeleaf属性,比如同时写
action和th:action,Thymeleaf会优先用th:action,但最好只保留th:前缀的属性。
内容的提问来源于stack exchange,提问作者Moe
相关产品推荐
相关产品推荐

