Spring Boot+Thymeleaf编辑用户出现404错误,寻求排查方案
解决Spring Boot + Thymeleaf编辑用户时404错误的问题
我是Spring Boot和Thymeleaf新手,现有用户列表展示在表格中,每个用户旁的编辑按钮本应打开预填充用户详情的可编辑表单,但点击后出现404未找到错误。
相关代码
用户列表表格代码
<table class="table table-striped table-advance table-hover"> <tbody> <tr> <th><i class="icon_profile"></i> Firstname</th> <th><i class="icon_profile"></i>Lastname</th> <th><i class="icon_profile"></i>Username</th> <th><i class="icon_profile"></i>Roles</th> <th></th> <th><i class="icon_cogs"></i> Action</th> </tr> <tr th:each="user:${users}"> <td th:text="${user.firstname}">Firstname</td> <td th:text="${user.lastname}">Lastname</td> <td th:text="${user.username}">Username</td> <td th:text="${user.roles}">Roles</td> <td><a th:href="@{/user/Edit/{id}(id=${user.id})}">Edit</a></td> </tr> </tbody> </table>
控制器编辑方法
@GetMapping("/users/edit/{id}") public String editUser(@PathVariable("id") Long id, Model model) { User user = userService.get(id); List<Role> listRoles = userService.listRoles(); model.addAttribute("user", user); model.addAttribute("listRoles", listRoles); return "user_form"; }
新增用户方法
@PostMapping(value="users/addNew") public RedirectView addNew(User user, RedirectAttributes redirect, Model model) throws QrGenerationException { userService.save(user); RedirectView redirectView= new RedirectView("/login",true); redirect.addFlashAttribute("message", "You successfully registered! You can now login"); return redirectView; }
UserService保存方法
public void save(User user){ Role roleUser = roleRepository.findByName("User"); user.addRole(roleUser); user.setPassword(encoder.encode(user.getPassword())); userRepository.save(user); }
问题原因及解决方案
404错误的核心原因是URL路径不匹配:
- 页面中生成的编辑路径是
/user/Edit/{id}(user为单数、Edit首字母大写) - 控制器映射的路径是
/users/edit/{id}(users为复数、edit全小写)
修复步骤
- 修正页面中的URL路径,推荐使用Thymeleaf更规范的URL变量写法,保证和控制器路径完全一致:
<a th:href="@{/users/edit/{id}(id=${user.id})}">Edit</a>
- 额外检查项:
- 确认控制器类是否带有
@RequestMapping前缀(比如@RequestMapping("/admin")),如果有,页面URL需要加上对应前缀(如@{/admin/users/edit/{id}(id=${user.id})}) - 确认
user_form.html模板文件放在src/main/resources/templates/目录下(Spring Boot默认模板路径) - 验证
userService.get(id)能正常查询到用户,避免因数据查询异常引发的间接问题
- 确认控制器类是否带有
内容的提问来源于stack exchange,提问作者Jaiylon
相关产品推荐
相关产品推荐

