1

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";
    }
}
Bartek K
  • 41
  • 5
  • What's wrong with returning a 400 status code and detailing what corrective actions the user needs to take? – JonK May 20 '20 at 10:05
  • Probably nothing. But I want errors to be presented under each field of the form. – Bartek K May 20 '20 at 10:33
  • You can still do that with a traditional 400 response, the response just needs to inform the client which field(s) were in error – JonK May 20 '20 at 13:59

0 Answers0