I am learning spring-mvc and I am doing a simple crud.
I have a list of items with a big add button on top of it.
When the user clicks add it will redirect to /item/add where the view is a form.
Now, when the user loads a new item I want to show a msg in the list saying something like:
“Item added successfully”
I noticed that I can do something like:
If ( noErrors ) {
model.addAttribute("Item added successfully");
return new ModelAndView("redirect:/item", model);
}
But I didn’t manage to get it working.
Any idea?
When you use
model.addAttribute(myObject), by convention you create a reference in the model tomyObjectkeyed by aStringderived from the name of the class ofmyObject.For example, if I add an instance of the
MyUserclass:model.addattribute(myUserInstance), then I will be able to access that object on the model by the key"myUser".Things get tricky when your object is a String, because there’s no obvious class to use to generate the key in the model.
Try instead specifying your own key:
model.addAttribute("statusMessage", "item added successfully"). Then in your view, you simply access the object by looking forstatusMessageon the model:<c:out value="${statusMessage}" />