方法不允许,状态 = 405,使用 Thymeleaf 的 HTML 形式

Method Not Allowed, status=405, HTML form using Thymeleaf

我使用 Thymeleaf 制作了一个表单,但 运行 遇到了这个问题。 我看了很多文章,但没有找到任何解决方案。
您可以建议任何解决方案吗?

项目控制器 ->

@Controller
public class Controllers {

@GetMapping("/home")
public ModelAndView home(){
    System.out.println("User is in Homepage");
    return new ModelAndView("index");
}

@GetMapping("/service")
public ModelAndView service(){
    System.out.println("User is in Service Page");
    return new ModelAndView("service");
}

@GetMapping("/about")
public ModelAndView about(){
    System.out.println("User is in About page");
    return new ModelAndView("about");
}

这是用于提交表单的控制器 Class ->

 @Controller

public class SavingUser{

@Autowired
private UserRepository userRepository;


@PostMapping("/registerUser")
public ModelAndView user(@ModelAttribute Customer customer, ModelMap model){
    System.out.println("User in registration page..");
    userRepository.save(customer);
    model.addAttribute("saveUser", customer);
    return new ModelAndView("index");
 }
}

这是我的 HTML 表格 -

    <div id="form">
    <form action="registerUser" th:action="@{/registerUser}"  th:object="${saveUser}" method="POST">
        <br />
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        <label for="name">Your Name:</label><br />
        <input type="text" th:field="*{name}"  placeholder="" /><br />

        <label for="suburb">Your Suburb</label><br />
        <input type="text"  th:field="*{suburb}"  placeholder="" /><br />

        
            <input class="submit" type="submit" value="Submit"  />
            <br /><br />
        </div>
    </form>
    </div>

我尝试删除 action="",但还是没用。

好吧,根据我在代码中看到的情况,您错过了控制器中用于实际显示页面的 @GetMapping 方法。不太清楚您在哪一步获得 405 状态。如果您还从控制台添加相关的异常消息,这将很有用。

编辑: 要回答最初的问题,您会得到 405,因为在 Post 控制器中,您向“/services”发出了 POST 请求,该请求不存在(服务仅存在 GET)。

    @PostMapping("/registerUser")
    public ModelAndView user(@Valid @ModelAttribute Customer customer, BindingResult result, ModelMap model){
        [...]
        return new ModelAndView("service"); // this makes a POST to "service" endpoint!
    }

要更正该问题,您必须像这样重定向到该页面:

    @PostMapping("/registerUser")
    public ModelAndView user(@Valid @ModelAttribute Customer customer, BindingResult result, ModelMap model){
        [...]
        return new ModelAndView("redirect:/service"); // this makes a GET to "service" endpoint
    }

撇开这一点不谈,还有很多可以改进的地方。首先,您没有在项目中使用 Thymeleaf。不会处理 Thymeleaf 标记。要使用它,您必须首先添加依赖项,然后将 Thymeleaf 配置为您的 HTML 解析器。完成所有操作的正确方法详见 here.

此外,我真的建议阅读 Thymeleaf documentation 并遵循一些教程以了解其工作原理。