Home > Software design >  Spring boot addFlashAttribute not displaying message in HTML
Spring boot addFlashAttribute not displaying message in HTML

Time:04-29

I've been searching here and online how to use addFlashAttribute in the best way and it's not working for me no matter what I do. I have a Student model which I'm trying to update and flash message of success or fail. The database and all the queries do work and I get redirected to the showStudentDetail page, it's just the message that doesn't show. Here is the code:

StudentService:

public String updateStudent(Student student) {
    if(studentDAO.update(student))
        return "update student was successful!";
    return "error: failed to update student, please try again";
}

public Student getStudentInfo(String username) {
    Student student = studentDAO.get(username);
    return student;
}

StudentController:

@PostMapping("/updateStudent")
public String updateStudent(@ModelAttribute("student") Student student, RedirectAttributes redirectAttrs) {
    String res = studentService.updateStudent(student);
    redirectAttrs.addAttribute("username", student.getUsername()).addFlashAttribute("message", res);
    return "redirect:/students/{username}/details";
}

@GetMapping("/students/{username}/details")
public String showDetailPage(@PathVariable String username, Model model) {
    Student student = studentService.getStudentInfo(username);
    model.addAttribute("student", student);
    return "student_detail";
}

student_detail (div not showing)

<div>
    <div th:if="${param.username}"  role="alert" th:text="${param.message}"></div>
</div>

CodePudding user response:

The name of the model in the controller is student, but in the view you are using "param" name. Change "param" to "student".

CodePudding user response:

I finally solved this problem by changing to message instead of param.message. I really don't know why now it's working but that's the solution to my problem.

only change the html to this:

<div th:if="${message}"  role="alert" th:text="${message}"></div>
  • Related