0

I am currently working on a program using spring boot and thymeleaf and encountered something strange. After submitting a form with th:action="/addEmployee", it does redirect me to the desired view, but the url looks like this 'http://localhost:8050/addEmployee?' instead of this 'http://localhost:8050/addEmployee'. It adds a ? mark even tough I do not want to add pathParams.

View:

<!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org" lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Departments</title>
    </head>
    <body>
        <h1>Department Administration</h1>
        <form method="get" th:action="@{/addEmployee}">
        <div>New Employee: <button type="submit">Add</button></div>
    </form>
  
   </body>
   </html>

Controller:

   @Slf4j
   @Controller
   @RequestMapping("/addEmployee")
   @SessionAttributes({"department", "sortOrder"})
   @RequiredArgsConstructor
   public class EmployeeController {

       private final EmployeeRepository employeeRepository;


       @GetMapping
       public String displayForm(Model model, @SessionAttribute("department") Department department,
                              @SessionAttribute("sortOrder") Boolean sortOrder){
           model.addAttribute("department", department);
           model.addAttribute("employee", new Employee());

           return "employeeView";
       }

   }

I don't really know what went wrong, since the unexpected question mark did not appear on my previous projects.

Let me know if you need additional code.

Appreciate it!

Kil4E04
  • 15
  • 4
  • 1
    Is there a reason why you are using a GET (`method="get"` and `@GetMapping`) instead of a POST here? (even with an empty form). – andrewJames Jan 23 '23 at 20:01
  • https://stackoverflow.com/questions/504947/when-should-i-use-get-or-post-method-whats-the-difference-between-them – riddle_me_this Jan 23 '23 at 21:39

1 Answers1

2

This is because GET carries request parameter appended in the URL string while POST carries request parameter in message body. You should change your syntax to

<form method="post" th:action="@{/addEmployee}">

Your controller should be annotated with @PostMapping for this method.

You'll want to follow the examples in the docs more closely as far as the controller.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80