It’s all to common for beginners of spring to stumble upon what may look like odd spring problems. Most users think that these are bugs while more often than not they are expected spring behaviour. I myself have stumbled upon my fair share of such problems.
One such problem is clearing the data contained within the formBackingObject (or command object) after a successful submit. If your form view and success view are the same then the form will display the same data as what the user submitted. It’s because by default, all forms being session forms, spring stores this formBackingObject in the session and after a submit, display data contained in this object in the view. It’s what spring is supposed to do.
The easiest way to clear your data is to have a method in your command object itself. The command object then looks something like this :
public class AddCategoryForm {
private int categoryId;
private String categoryName;
private String description;
public void clearValues() {
setCategoryName("");
setDescription("");
}
}
A common misconception is that creating a new command object in the onSubmit method of your controller will clear the values. This does not remove the command object which is already sitting in your session from which the values in the view are picked up. Which is why the approach doesn’t work. In your controller :
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
// ...
AddCategoryForm form = (AddCategoryForm) command;
form.clearValues();
//...
}
Thats it, despite having the same form and success view your view will now display an empty form instead of values with which it was submitted.
No related posts.