RedirectAttributes not loading in Controller after redirect until after manual page refresh

  Kiến thức lập trình

Summary: I have a user sign up page with email and password fields and if they try to register with an email already in use, it throws an error which is handled by creating an ErrorDTO, set it as a redirect flash attribute and then redirects back to the sign up page.

Problem: When the redirect is completed, the flash attribute is not being seen in the signup page’s Controller – until I manually refresh the page and click submit – finally catching the error and displaying it on the form. Another piece of interesting information is that it doesn’t require submitting the form first, if I visit the page and immediately refresh manually, it will display the error correctly.

Here is the Controller for the form where you can see the ModelAttribute annotation to receive the ErrorDTO

@GetMapping("/signup")
    public String registerForm(Model model,
                               Principal principal,
                               HttpSession session,
                               HttpServletResponse response,
                               HttpServletRequest request,
                               @ModelAttribute("UserExistsError") ErrorDTO errorDTO) {

        if ((principal != null && principal.getName() != null)) {
            String userID = principal.getName();
            model.addAttribute("loginID", userID);
        }
        if (session != null) {
            response.addCookie(new Cookie("prevURL", request.getHeader("referer")));
        }
        if (errorDTO != null && errorDTO.getMessage() != null){
                model.addAttribute("UserError", true);
        }

        model.addAttribute("regDetail", new RegisterDTO());
        return "register";
    }

and here is the ExceptionHandler for this error

    @ExceptionHandler(UserAlreadyExistsException.class)
    public String handleUserAlreadyExistsException(RedirectAttributes redirectAttributes) {
        ErrorDTO error = new ErrorDTO();
        error.setMessage("UserExists");
        redirectAttributes.addFlashAttribute("UserExistsError", error);
        return "redirect:/signup";
    }

I have tried looking at different ways to handle the redirect in case there was something consuming it behind the scenes, but nothing I do has changed the behavior.

I also know for a fact that the exception is being thrown because despite the flash attributes not being seen by the controller post-redirect, the log is still displaying the exception is being handled.

LEAVE A COMMENT