Spring MVC Redirect - Tuong-Nguyen/Spring GitHub Wiki

Why do a redirect?

When user posts a form data and delegates the execution flow to another controller method, the problem occurs by refreshing the page before the first submission has completed may still result in a double submission

Do a redirect

With RedirectView

    @RequestMapping(value="/redirectWithRedirectView")
    public RedirectView redirectWithUsingRedirectRequest (Model model) {
        model.addAttribute("attribute", "redirectWithRedirectRequest");
        return new RedirectView("redirectedUrl");
    }
  • RedirectView will trigger a HttpServletResponse.sendRedirect() – which will perform the actual redirect

With Prefix redirect

    @RequestMapping(value="/redirectWithRedirectPrefix")
    public String redirectWithUsingRedirectPrefix(Model model) {
        model.addAttribute("attribute", "redirectWithRedirectPrefix");
        return "redirect:/redirectedUrl";
    }
  • The UrlBasedViewResolver (and all its subclasses) will recognize this as a special indication that a redirect needs to happen. The rest of the view name will be used as the redirect URL.

Send data

With RedirectAttributes

    @RequestMapping(value="/redirectWithRedirectAttributes")
    public String sendDataUsingRedirectAttributes(RedirectAttributes attributes) {
        attributes.addAttribute("attribute", "redirectWithRedirectAttributes");
        return "redirect:/redirectedUrl";
    }
  • Get RedirectAttributes value
    @RequestMapping(value="/redirectedUrl", params="attribute")
    public String getDataFromRedirectAttributes(Model model, @RequestParam("attribute") String attribute) {
        model.addAttribute("modelAttribute", attribute);
        return "home";
    }

With FlashAttributes

    @RequestMapping(value="/redirectWithFlashAttributes")
    public String sendDataUsingFlashAttributes(@ModelAttribute Project project, RedirectAttributes attributes) {
        attributes.addFlashAttribute("project", project);
        return "redirect:/redirectedUrl";
    }
  • After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL
  • Get data
    @RequestMapping(value="/redirectedUrl")
    public String getDataFromFlashAttributes(@Model model, @ModelAttribute Project project) {
        model.addAttribute("currentProject", project);
        return "home";
    }