Spring web app tutorial extras: Redirect Attributes

How to use Redirect Attributes in Spring Web MVC (which can contain Flash-scoped attributes).

In Java Blog Aggregator tutorial which is freely available on my GitHub account and on Javavids is a complete tutorial how to create it I have a registration form. When a new user registers successfully, I do a redirect to the same page with a request parameter "success=true". In the JSP file I check if the parameter success is true and if so, I will print text "Registration successfull".

I just found a better way how to do the same with the flash scoped redirect attribute, which is available since Spring 3.1.

In the method annotated with @RequestMapping add this parameter: "RedirectAttributes redirectAttributes" and after the user was saved successfully, add some flash attribute.

@RequestMapping(method = RequestMethod.POST)
public String doRegister(@Valid @ModelAttribute("user") User user, BindingResult result, RedirectAttributes redirectAttributes) {
  if (result.hasErrors()) {
    return "user-register";
  }
  userService.save(user);
  redirectAttributes.addFlashAttribute("success", "true");
  return "redirect:/register.html";
}

In the JSP file don't use a parameter, but an attribute.

<c:if test="${success eq true}">
  <div class="alert alert-success">Registration successfull!</div>
</c:if>

And we're done. There are two differences between this and previous approach:

  1. You don't see the parameter in URL.
  2. After the page refresh the attribute disappears.