Spring Boot+Thymeleaf报错:无法在null上找到属性'userName'
问题修复:Spring Boot + Thymeleaf 登录功能 SpelEvaluationException 异常
核心错误原因
控制器向Model注入的属性名称与Thymeleaf模板引用的对象名称不匹配,导致模板渲染时loginData为null,访问其属性userName抛出EL1007E异常。同时表单绑定、成功页数据传递也存在多处错误。
分步修复代码
1. 修复控制器(MyController)
修改formHandler方法的Model属性名称,确保与模板中的loginData一致;同时在processform方法中把登录数据传入成功页:
@GetMapping("/form") public String formHandler(Model m ) { System.out.println("opening form"); // 注入与模板匹配的属性名loginData m.addAttribute("loginData", new LoginData()); System.out.println("YAY"); return "form1"; } // 处理表单提交 @PostMapping("/process") public String processform(@ModelAttribute("loginData") LoginData loginData, Model m) { System.out.println(loginData); // 将登录数据传入成功页 m.addAttribute("loginData", loginData); return "success"; }
- 修改点:把
m.addAttribute("login", new LoginData())改为m.addAttribute("loginData", new LoginData());在processform方法添加Model参数,将loginData传入成功页。
2. 修复登录表单(form.html)
修正密码输入框的类型和属性绑定,确保与loginData的字段匹配:
<div class="container"> <div class="row mt-5"> <div class="col-md-6 offset-md-3"> <form th:action="@{/process}" method="post" th:object="${loginData}"> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="text" name="userName" class="form-control" th:value="${loginData.userName}" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" <!-- 修正为password类型 --> name="email" th:value="${loginData.email}" <!-- 修正为绑定email字段 --> class="form-control" id="exampleInputPassword1"> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Check me out</label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div>
- 修改点:密码输入框
type从email改为password;th:value从${loginData}改为${loginData.email}。
3. 修复成功页(success.html)
修正属性引用的名称(与控制器传入的loginData小写一致):
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Success</title> </head> <body> <h1>Welcome to this success page</h1> <h1 th:text="${loginData.userName}"></h1> <!-- 修正为小写loginData --> <h1 th:text="${loginData.email}"></h1> <!-- 修正为小写loginData --> </body> </html>
- 修改点:把
${LoginData.userName}和${LoginData.email}改为${loginData.userName}和${loginData.email}。
额外优化建议
使用Thymeleaf的th:field进行表单绑定,会自动处理name、value等属性,更简洁且不易出错,示例:
<input type="text" class="form-control" th:field="*{userName}" id="exampleInputEmail1" aria-describedby="emailHelp"> <input type="password" class="form-control" th:field="*{email}" id="exampleInputPassword1">
使用th:field时,表单的th:object="${loginData}"必须存在,这样*{userName}会自动对应loginData.userName。
内容的提问来源于stack exchange,提问作者Sabertooth
相关产品推荐
相关产品推荐

