Issue
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}" class="alert alert-info" role="alert" th:text="${param.message}"></div>
</div>
Solution
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}" class="alert alert-info" role="alert" th:text="${message}"></div>
Answered By - Ofir Sasson
Answer Checked By - David Goodson (JavaFixing Volunteer)