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!
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.