Friday, 26 July 2013

My Findings with ModelDriven Struts Action

We are well aware of the usual action classes of Struts- values of the fields entered in UI populate the corresponding action properties. In case of ModelDriven action class, the properties of its model class get populated. Here is an example of it:


public class EmployeeRegistrationAction extends ActionSupport implements ModelDriven<EmployeeData>{

 private EmployeeData employeeData = new EmployeeData();

 
 public EmployeeData getModel() {
  return employeeData;
 }

 //Rest of the methods

}


public class EmployeeData implements Serializable{

 private String firstName;
 private String lastName;
 private String city;

 //setters & getters

}


The next step is to implement the getModel() method in such a way that it returns the application domain object, in our example we return the EmployeeData object. We can either use ModelDriven<Object>, where getModel will return Object or can specify the model class as above.
Prerequisite for using such action class is that it should implement ModelDriven interface, for which Model Driven Interceptor should be applied to action. Since this interceptor is part of the default interceptor stack, it is applied to all actions by default. Wow...we don't have to do anything out of the way to use it!

JSP:

<s:form method="POST" action="/registration.html" name="registrationform" enctype="multipart/form-data" id="registrationform">

     <s:textfield name="firstName" placeholder="First Name"/>
     <s:textfield name="lastName" placeholder="Last Name"/>
     <input type="submit" class="button" value="Create Employee"/>

</s:form>


Since I did not want to navigate to any other page and wanted the json response by staying on same page, I used ajaxSubmit(). I'd used ajaxSubmit earlier too and json response was returned just as I expected. Xml entry:

<action name="registration" class="employeeRegistrationAction" method="createEmployeeRecord">

 <result type="json"></result>

</action>


Javascript:

var registrationFormOptions = {

 resetForm : false,// reset the form after successful submit
        success   : showRegistrationResponse

    };


$("#registrationform").validate({

 submitHandler:function(form){
 //perform not-null validations. If fine,submit. else show validation error messages
 $(form).ajaxSubmit(registrationFormOptions);

 }
});

But in case of ModelDriven, json response that I was getting, was surrounded by <pre style="word-wrap: break-word; white-space: pre-wrap;"> tag. I thought of extracting json sitting inside the <pre> tag, in javascript. Thankfully I was saved from it, just one minor addition and it worked:


var registrationFormOptions = {

 resetForm : false,// reset the form after successful submit
 success : showRegistrationResponse,
 dataType: 'json'
};


Addition of dataType: 'json' in the options worked wonders. I was getting a clean json response!


No comments:

Post a Comment