首页 > 解决方案 > 不支持 Spring MVC 请求方法“POST”-> HTTP 405

问题描述

卡住了约 4 个小时,想知道 Spring MVC/thymeleaf 应用程序中的错误在哪里。
我的本地目标是在主页提交登录/传递表单后呈现 admin.html。

控制器:

@Controller
public class HomeController {
        @GetMapping("/")
        public String getHome(Model m) {
            m.addAttribute( "user",new User());
            return "/home";
        }
        @PostMapping("/")
        public String getSubmit(@ModelAttribute User user){

            return "/admin";
        }
}

主页.html:

  <form action="#" th:action="@{/admin}" th:object="${user}" method="post">
            <p class="txt">Name: <input type="text" th:field="*{name}"/></p>
            <p class="txt">Password: <input type="text" th:field="*{password}"/></p>
            <p><input class="button" type="submit" value="Submit" />
                <input class="button" type="reset" value="Reset" /></p>
        </form >

用户等级:

@Data
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private String password;
    private boolean isAdmin;
    private String address;
}

所以我用谷歌搜索了很多想法,从 pom.xml 中删除了 spring 安全性,
尝试将 @RequestedMapping 与 RequestMethod.PUT 一起使用, - 没办法,它不起作用。

标签: javaspringspring-bootmodel-view-controllerthymeleaf

解决方案


您的表单引用th:action="@{/admin}"为目标。您的控制器不映射/admin,但只有 root /

您必须将目标更改为/.

如果你想渲染一个模板/admin,那么你的回报是正确的。如果你想重定向到/admin一个新的控制器可以处理这个,所以你必须改写redirect:/admin


推荐阅读