Search code examples
springspring-bootthymeleaf

Request method 'GET' not supported Spring Booth with Thymeleaf


I am building a very simple crud app using Spring boot, Jpa and Thymeleaf, but I am stuck at a "Request method 'GET' not supported" problem. I get this error whenever I want to access the /add page through which I can add a new student. The snippets associated with this error are as below:

Thymeleaf form:

<h1>Form</h1>
<form action="#" th:action="@{/add}" th:object="${addStudent}" 
   method="post">
    <p>Full name: <input type="text" th:field="*{fname}" /></p>
    <p>Major: <input type="text" th:field="*{major}" /></p>

    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>

Controller addNewStudentMethod

@PostMapping("/add")
public String addNewStudent( @ModelAttribute StudentEntity studentEntity, Model model) {

    model.addAttribute("addStudent",studentRepository.save(studentEntity) );
    return "/allstudents";
}

The error I get:

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

Thanks,


Solution

  • You have some issues with how you have it set up. What you may want is:

    @GetMapping("/add")
    public String addNewStudent(Model model) {
    
        model.addAttribute("studentEntity", new StudentEntity()); //create a new bean so that your form can bind the input fields to it
        return "add"; //let's say add.html this is the name of your form
    }
    
    @PostMapping("/add")
    public String addNewStudent( @ModelAttribute StudentEntity studentEntity, Model model) {
    
      //call any service methods to do any processing here
      studentRepository.save(studentEntity);
      return "redirect:/allstudents";  //this would be your confirmation page
    }
    

    Your add.html form would have something like:

    <form th:object="${studentEntity}" th:action="@{/add}" method="post" action="allstudents.html">
    <!-- input fields here --->
    </form>
    

    Note that the th:object is what you added to the model in the @GetMapping method.