You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot API编辑按钮失效,出现404 Not Found错误求助

问题分析与解决步骤

1. 表单请求路径与方法不匹配

  • 前端表单的th:action仅写了@{/edit},但后端没有对应/edit的POST/PUT接口;同时HTML原生表单不支持PUT请求,需要通过Spring的_method隐藏域模拟PUT请求。
  • 修正表单代码:
<form th:action="@{/edit/{id}(id=${userEntity.id})}" method="post" th:object="${userEntity}">
    <!-- 添加隐藏域,让Spring识别为PUT请求 -->
    <input type="hidden" name="_method" value="PUT"/>
    <div><label> New username : <input th:field="*{name}" type="text" name="username"/> </label></div>
    <div><label> New password: <input th:field="*{password}" type="password" name="password"/> </label></div>
    <div><input type="submit" value="Save"></div>
</form>

2. Controller的PUT方法参数缺失

  • 当前@PutMapping("/edit/{id}")方法仅接收了id,没有绑定前端提交的修改后用户数据,需添加@ModelAttribute接收表单对象:
@PutMapping("/edit/{id}")
public String editUser(@PathVariable(name = "id") Long id, @ModelAttribute UserEntity userEntity) {
    userService.updateUser(id, userEntity);
    // 重定向到主页,避免表单重复提交
    return "redirect:/";
}

3. UserService的updateUser方法逻辑错误

  • 现有方法只是将用户的姓名和密码设为原有值,未实现更新逻辑;同时参数设计不合理,需接收id和修改后的用户对象:
public UserEntity updateUser(Long id, UserEntity updatedUser) {
    UserEntity userEntity = userRepo.findById(id)
            // 处理用户不存在的情况,避免空指针
            .orElseThrow(() -> new RuntimeException("User not found with id: " + id));
    // 更新前端传入的姓名和密码
    userEntity.setName(updatedUser.getName());
    userEntity.setPassword(updatedUser.getPassword());
    return userRepo.save(userEntity);
}

4. 确认HiddenHttpMethodFilter启用

  • Spring Boot 2.2及以上版本默认已开启HiddenHttpMethodFilter,该过滤器负责识别表单中的_method隐藏域,将POST请求转换为PUT请求,无需额外配置。

额外提示

  • 避免直接调用Optional.get(),建议用orElseThrow处理用户不存在的异常场景。
  • 更新完成后使用重定向而非直接返回页面,防止用户刷新页面重复提交表单。

内容的提问来源于stack exchange,提问作者OGKAZA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:57:14