如何修复“org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法‘POST’?”

2024-02-27

所以我收到警告

 WARN  [org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] (default task-2) Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported] 

当我访问以下网址时http://localhost:8080/ProjectFE/uregistration网站显示

HTTP 405 方法不允许

这是我的控制器代码:

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import model.daoimpl.UserinfoDaoImpl;
import model.dao.IUserinfoDAO;
import model.entity.Userinfo;

@Controller
public class RegistrationController {
    @RequestMapping(value="/registration",method = RequestMethod.GET)
    public String addRegistrationPage() {
        return "registrationpage";
    }
    @RequestMapping(value="/uregistration",method = RequestMethod.POST)
    public String addURegistrationPage(@ModelAttribute("User")Userinfo u) {
        IUserinfoDAO iu = new UserinfoDaoImpl();
        boolean b = iu.insertInfo(u);
        if(b)
            return "success";
        else
            return "registrationpage";
    }

}

所以我该怎么做 ?另外,如果需要任何其他代码,请发表评论,我将编辑帖子, 谢谢。


我通过在向服务器发出 ajax 请求时简单地添加 spring 文档中提到的 csrf 配置来解决我的问题。请记住,csrf 在 spring 中默认启用,您必须禁用它(不好)或启用它。 链接在这里

https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html

所以我添加了 <meta name="_csrf" th:content="${_csrf.token}" /> <meta name="_csrf_header" th:content="${_csrf.headerName}" />

<script type="application/x-javascript">
   (function () {
       var token = $("meta[name='_csrf']").attr("content");
       var header = $("meta[name='_csrf_header']").attr("content");
       $(document).ajaxSend(function(e, xhr, options) {
          xhr.setRequestHeader(header, token);
       });
   });
</script>

在我的 html 头部和我提交的表单中,我包含了这个隐藏的小输入,我的输入对我有用。希望对你有帮助。

<input type="hidden" th:name="${_csrf.parameterName}"
                        th:value="${_csrf.token}" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复“org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法‘POST’?” 的相关文章

随机推荐