Spring MVC Form: Errors Using Ajax

I have a question related to Spring 3 MVC, Ajax and form: errors.

I have a form that I submit to the server and I use Spring MVC. I have all the checks, controllers, etc. Configured and working fine. When I submit data that does not pass validation, I return an error message and it displays on the form according to my form: error tags in my jsp.

My question is ...

If I want to convert to an Ajax approach, can I still use the entire infrastructure of the โ€œnormalโ€ Spring MVC application (ie features of validation and form: errors) to return errors to (and displayed on) in the browser? I see how to send Ajax requests, but I don't see how (or if) I can still use the form: jsp errors.

Does anyone know if this can be done, and if so, point me in the appropriate general direction?

Thanks in advance.

+4
source share
3 answers

You cannot, because tags like <form:errors> are evaluated on the server side and insert error messages / elements into the HTML content of the HTTP response. Since an AJAX request to the server usually returns XML or JSON for the response (rather than HTML), which is then parsed by client-side JavaScript, there is no point in which Spring can bind to the request / form and add a message error to the content.

+5
source

I used quite a lot of AJAX when submitting forms in Spring. Basically, what I did was that I created a form.jsp file, which then returns from an AJAX call. Since AJAX will return the entire form with all available form tags, I get all the benefits of server side validation.

So, if I have a page containing a form, I could, for example, have a div that acts as a form container

 <div id="form-container"> <form id="myform"> Normal form here ... </form> </div> 

And when I submit the form, I can load form.jsp using jQuery for example

 $('#myform').submit(function() { $('#form-container').load('ajax/somehandler'); }); 

So all you have to do is return form.jsp from the controller with all the normal connections, as well as with the non-AJAX approach. Do you have an idea?

+5
source

Not really, no. The form:error tag does its magic when the page is first created by the server side. If you do not regenerate the page server because you used ajax, none of them will be launched. The Errors object itself does not return fully to the client. You can serialize it to JSON, I suppose, but there are so many things that you don't need. Plus, of course, he usually only has codes, not actual messages, and he needs a message source to search for translations.

On the bottom line, you will need to send errors manually and handle the error messages themselves in javascript when returning an ajax response.

+4
source

All Articles