Thymeleaf SpringEL表达式异常及字段无法解析问题求助
问题分析与修复方案
核心问题1:控制器未将User对象传入视图
你的UserController的register方法接收了User参数,但没有把这个对象添加到Spring的Model中,导致Thymeleaf在success.html里找不到${user}变量,因此会提示“Cannot resolve 'username'”“Cannot resolve 'password'”。
核心问题2:Thymeleaf表达式拼写错误
success.html里的<h3>[[*{usesrname}]],success! </h3>存在拼写错误,usesrname应该改为username。
可选优化:User类的构造方法问题
你的User类用了@AllArgsConstructor,生成的构造方法需要传入id、username、password三个参数,但表单提交时只传了后两个。虽然SpringMVC能通过反射创建对象,但建议添加无参构造方法,避免潜在的参数绑定异常。
修复后的代码
1. 修改UserController.java
package com.test01.controller; import com.test01.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @GetMapping("/register") public String doDefault(){ return "register"; } @PostMapping("/register") public String register(User user, Model model) { // 将User对象添加到Model中,供Thymeleaf视图调用 model.addAttribute("user", user); return "success"; } }
2. 修改User.java(推荐)
package com.test01.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; // 添加无参构造方法,兼容表单参数绑定 @NoArgsConstructor @AllArgsConstructor @Data public class User { private Integer id; private String username; private String password; }
3. 修改success.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>success</title> </head> <body th:object="${user}"> <!-- 修正拼写错误:usesrname → username --> <h3>[[*{username}]],success! </h3> <table border="0"> <caption>Your registration information is</caption> <tr> <td>username:</td> <td th:text="*{username}"></td> </tr> <tr> <td>password:</td> <td th:text="*{password}"></td> </tr> </table> </body> </html>
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

