If I have errors on the form, I want to redirect the view to the get method. Is this a good practice?
In the POST method, I have employee and addresses. The first is the Employee object, the second is the list of two addresses. How to transfer them back to the view to the GET method?
@GetMapping("/new")
public String showCreateFormForEmployeeAndAddresses(Model model) {
if(addressService.getCheck()== false) {
for (int i = 1; i <= 2; i++) {
addressService.newAddress(new Address());
}
model.addAttribute("employee", new Employee()).addAttribute("form", addressService);
}else {
model.addAttribute("employee", ???).addAttribute("form", ???);
}
return "new_employee_form";
}
@RequestMapping(value = "/employees", method = RequestMethod.POST)
public String saveEmployeeAndAddress(RedirectAttributes redirectAttributes,
@ModelAttribute @Valid Employee employee,
BindingResult bindingResultEmployee,
@ModelAttribute @Valid AddressRepository addresses,
BindingResult bindingResultAddressRepository, Model model) {
if(bindingResultEmployee.hasErrors() || bindingResultAddressRepository.hasErrors()) {
return "redirect:/new";
} else{
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable runnableEmployee = () -> employeeService.saveEmployeeToDB(employee);
List<Address> addressesFromForm = addresses.getAddresses();
Runnable runnableAddress = () -> addressService.saveAddressToDB(addressesFromForm);
executor.submit(runnableEmployee);
executor.submit(runnableAddress);
return "redirect:/employees";
}
}