Can't seem to get addFlashAttribute message to display. It works on another controller but not on this one. My error check (if (.ingredientRepository..;)) appears to work and the object is NOT saved due to error, however. the message is either not passed or just doesn't display.
< p th:if="${ingredientError}" th:text="${ingredientError}" class="alert alert-danger" /></ p>
Controller Mappings:
@GetMapping("")
public String index(Model model, HttpServletRequest request) {
model.addAttribute("ingredients", ingredientRepository.findAll(Sort.by(Sort.Direction.ASC, "name")));
model.addAttribute(new Ingredient());
return "ingredients/index";
}
@PostMapping("add")
public String addIngredient(@ModelAttribute @Valid Ingredient newIngredient, Errors errors, Model model, RedirectAttributes ra) {
if (errors.hasErrors()) {
model.addAttribute("ingredients", ingredientRepository.findAll(Sort.by(Sort.Direction.ASC, "name")));
model.addAttribute("errors", errors);
return "ingredients/index";
}
if (!ingredientRepository.findByName(newIngredient.getName()).isEmpty()) {
ra.addFlashAttribute("ingredientError", "Ingredient already exists.");
return "redirect:";
}
ingredientRepository.save(newIngredient);
return "redirect:";
}
Your th:if is faulty I believe. It should be <p th:if="${ingredientError:= null}" th:text="${ingredientError}" class="alert alert-danger" /></ p>
.
th:if="${ingredientError}"
only works for pressent boolean variables.
When requesting a redirect via the return "redirect:"
, you should include the url to redirect to. For example: return "redirect:/ingredients"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.