Struts 2 supports DWR/Dojo plugin for AJAX and other JavaScript. It also has a plugin for jQuery. But as a developer, I feel that using the plugins will couple the front-end and plugin more tightly. If you want to avoid it, we can write our own custom JavaScript AJAX methods. But the drawback is more coding. Plus point is full control is with you and no coupling with any plugin.
In this example, I am trying to do an AJAX validation to a form with normal jQuery.
The key changes in configurations are:
- Add jsonValidationWorkflowStack interception to the action class in struts.xml
- Add these 2 hidden variables inside your form and set them to true
- struts.enableJSONValidation
- struts.validateOnly
- Remove your normal <s:submit/> button or override its onsubmit event to do your AJAX things.
Step: 1 – Add jsonValidationWorkflowStack interception to the action class in struts.xml
<action name=...> <interceptor-ref name="jsonValidationWorkflowStack" /> <result name="input">....</result> </action>
Step: 2 – Adding hidden variables to the form
<s:form action="login" id="submitForm"> <legend>Login</legend> <s:textfield name="username" /> <s:password name="password" /> <s:hidden name="struts.enableJSONValidation" value="true"></s:hidden> <s:hidden name="struts.validateOnly" value="true"></s:hidden> <input type="button" id="submitLogin" /> </s:form>
Step: 2 – Remove your normal <s:submit/> button or override its onsubmit event
Here I am using a normal button for simplicity.
<input type="button" id="submitLogin" />
And this is the JavaScript that does the AJAX Submission.
$(document).ready(
function () {
$("#submitLogin").click(
function () {
$.post($("#submitForm").attr("action"), $("#submitForm").serialize(), function (data) {
//Here the data will be a json.
//Parse the json and implement the validation error logic.
});
});
});







