Home > database >  Java Spring Boot/Thymeleaf redirectAttribute addFlashAttribute message NOT showing in redirect page
Java Spring Boot/Thymeleaf redirectAttribute addFlashAttribute message NOT showing in redirect page

Time:09-08

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}" /></ 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:";
}

CodePudding user response:

Your th:if is faulty I believe. It should be <p th:if="${ingredientError != null}" th:text="${ingredientError}" /></ p>.

th:if="${ingredientError}" only works for pressent boolean variables.

CodePudding user response:

When requesting a redirect via the return "redirect:", you should include the url to redirect to. For example: return "redirect:/ingredients"

  • Related