I'm validating a form using the Validator
interface with Spring MVC 3.0.2 using SimpleFormController
. The following is the controller class which extends SimpleFormController
.
@SuppressWarnings("deprecation")
final public class Temp extends SimpleFormController
{
public Temp()
{
setCommandClass(ValidationForm.class);
setCommandName("validationForm");
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
{
ValidationBean validationBean=(ValidationBean) command;
ModelAndView mv=new ModelAndView("Temp", "validationForm", validationBean);
if(errors.hasErrors())
{
System.out.println("error");
}
else
{
System.out.println("name = "+validationBean.getUserName());
}
return mv;
}
@Override
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception
{
ModelAndView mv=new ModelAndView("Temp", "validationForm", errors.getTarget());
return mv;
}
}
There is no question about form-validation. It works fine. The only question here is that when I use the showForm(...){...}
method as shown above, the error messages are not displayed because this method calls when the JSP page is loaded and also, after the onSubmit()
method completes (In case, the page is submitted by clicking the submit button on the JSP page).
When the page is submitted by clicking the submit button, the command object which is errors.getTarget()
(or getCommand(request)
) in the showForm()
method (which is called after the onSubmit()
method) contains no error messages to be displayed on the page. The command object (or domain object) is different from the command object in the onSubmit()
method. (and therefore, when the showForm()
method is commented out, it displays error messages)
I need to use the showForm()
method to display a list of data from the database when the page is either submitted or loaded.
Of course, the referenceData()
method as shown below does the trick.
protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception
{
Map map=new HashMap();
return map;
}
but I want to stick at the showForm()
method. Is there a fair way to display error messages while using the showForm()
method while validating a form?