Issue
**Hi everyone. I ran into a problem while developing a web application. The saveEmployee method does not work properly and throws the corresponding error. In the project I use Spring-boot + Thymeleaf. I think there is an error in these two files or a problem in the configuration. But so far I haven't found anything. **
myRestController.java
@Controller
@RequestMapping("/shop")
public class myRestController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/allEmployees")
public String allEmployees(Model model) {
List<Employee> employees = employeeService.getAllEmployees();
model.addAttribute("employeesList", employees);
return "allEmployees";
}
@GetMapping("/allEmployees/{name}")
public String getEmployeeByName(@PathVariable String name, Model model) {
List<Employee> employees = employeeService.findAllByName(name);
model.addAttribute("employeesList", employees);
return "allEmployees";
}
@GetMapping("/newEmployee")
public String addEmployee(Model model) {
Employee employee = new Employee();
model.addAttribute("employee", employee);
return "addNewEmployee";
}
@RequestMapping()
public String saveEmployee(@ModelAttribute("employee") Employee employee){
employeeService.saveEmployee(employee);
return "index";
}
addNewEmployee.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Add Employee</h1>
<form th:method="POST" th:action="@{shop/allEmployees}" th:object="${employee}">
<label for="name">Enter name:</label>
<input type="text" th:field="*{name}" id="name"/>
<br/>
<label for="surname">Enter surname:</label>
<input type="text" th:field="*{surname}" id="surname"/>
<br/>
<label for="department">Enter department:</label>
<input type="text" th:field="*{department}" id="department"/>
<br/>
<label for="salary">Enter salary:</label>
<input type="text" th:field="*{salary}" id="salary"/>
<br/>
<input type="submit" value="Create!">
</form>
<br><br>
</body>
</html>
Solution
In your myRestController.java
, I am not seeing any @PostMapping
defined. In addNewEmployee.html
, it appears you are attempting to call shop/allEmployees with a POST
rather than the GET
method. If your intention is to pass a body or form to the shop/allEmployees
endpoint, you may want to consider either changing your @GetMapping
to a @PostMapping
that accepts a @RequestBody
or creating an entirely new @PostMapping
that accepts a @RequestBody
.
Answered By - krlittle
Answer Checked By - Mildred Charles (JavaFixing Admin)