To use redirect attributes, you need to add org.springframework.web.servlet.mvc.support.RedirectAttributes as a parameter to your controller method. In the example code, I have this controller method to get started:
@PostMapping("/new")
public String create(@ModelAttribute("formData") CreateProductFormData formData,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "products/edit";
}
productRepository.save(formData.toProduct());
return "redirect:/products";
}
It shows the POST mapping to create a new product in the application. See Form handling with Thymeleaf if you need more information about how forms work with Thymeleaf.
We see that if there are no validation errors on the form, the browser will be redirected to the /products path.
If we want to show a message Product created on our list of products page, we can use RedirectAttributes like this:
@PostMapping("/new")
public String create(@ModelAttribute("formData") CreateProductFormData formData,
BindingResult bindingResult, RedirectAttributes redirectAttributes) { (1)
if (bindingResult.hasErrors()) {
return "products/edit";
}
productRepository.save(formData.toProduct());
redirectAttributes.addFlashAttribute("message", "Product created"); (2)
return "redirect:/products";
}
| 1 |
Inject RedirectAttributes as a parameter. |
| 2 |
Add a flash attribute with the key message and the value Product created. |
To now use this flash attribute, we can use it like any other Model attribute:
src/main/resources/templates/products/index.html
...
<th:block th:if="${message}"> (1)
<div th:replace="~{fragments :: success-message(${message})}"></div>
</th:block>
<ul class="mt-4 ml-4 list-disc">
<li th:each="product : ${products}">
<span th:text="${product.name}"></span> -
<span th:text="|€ ${product.price}|"></span> -
</li>
</ul>
...
| 1 |
Show a notification message if the message attribute is present. |
Screenshot of the notification after a product is added:
If you refresh the page, the message automatically disappears: