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

使用Spring MVC+AJAX更新数据库时出现405 Method Not Allowed错误求助

解决Spring MVC AJAX更新时的405(方法不允许)错误

首先,405错误的核心原因是你的AJAX请求使用的HTTP方法,和Spring MVC Controller接口声明的支持方法不匹配,再结合你给出的代码和请求URL,咱们一步步排查解决:

1. 先核对AJAX请求的HTTP方法

你的Controller接口明确标注了method=RequestMethod.PUT,这意味着它只接受PUT类型的请求。如果你的AJAX代码用了GET/POST(默认是GET),必然会触发405错误。

举个jQuery AJAX的正确示例,必须显式指定PUT方法:

$.ajax({
    url: "/my_project/activerutilisateur/zhangsan", // 这里要替换成实际的用户名,对应Controller的{username}
    type: "PUT", // 必须和Controller的method一致
    contentType: "application/json",
    data: JSON.stringify({/* 你的用户更新数据 */}),
    success: function(res) {
        console.log("更新成功:", res);
    },
    error: function(xhr) {
        console.error("请求失败:", xhr.statusText);
    }
});

2. 确保请求路径与Controller完全匹配

你的Controller路径是/activerutilisateur/{username},这里的{username}是路径变量,需要替换成实际的用户名(比如zhangsan)。而你的错误请求URL是/activerutilisateur/user——除非你的用户名就是"user",否则这个路径和Controller的映射不匹配,也可能导致405或404。

3. 完善Controller的参数绑定(避免隐性错误)

你的Controller方法需要正确接收路径变量和请求体的用户数据,记得加上@ResponseBody确保返回JSON(和produces配置对应):

@RequestMapping(value="/activerutilisateur/{username}", method=RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Utilisateur updateUtilisateur(@PathVariable String username, @RequestBody Utilisateur utilisateur) {
    // 可选:把路径里的username同步到用户对象中
    utilisateur.setUsername(username);
    return utilisateurDAO.updateUtilisateur(utilisateur);
}

4. 如果是表单提交(非纯AJAX),需配置方法转换过滤器

如果你的前端是用HTML表单提交(不是直接AJAX),浏览器默认只支持GET/POST,这时候需要通过HiddenHttpMethodFilter来模拟PUT请求:

  • 在web.xml中添加过滤器配置:
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
  • 表单中添加隐藏域声明实际请求方法:
<form action="/my_project/activerutilisateur/zhangsan" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <!-- 其他用户信息输入框 -->
    <button type="submit">激活用户</button>
</form>

5. 验证Spring MVC基础配置

确保你的Spring配置文件(比如spring-servlet.xml)开启了注解驱动,这是支持@RequestMapping、@RequestBody等注解的前提:

<mvc:annotation-driven />

按上面的步骤逐一排查,基本就能解决这个405错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:58:03