In my previous post on Spring and ExtJS, you might have noticed the usage of a class called ExtData in the methods of the ContactController. I didn’t explain it at the time, but want to clarify what it is and why I created it.
There is a lot of boilerplate code involved in sending a response back to a request from ExtJS. You’re always going to return a Map, which has a success property, and possibly data, total and message properties. A typical response would look like this:
This gets annoying after you’ve done it a couple dozen times in the same application, so like every good (lazy) programmer, I implemented a simple class to deal with this. Take a look at the
ExtData classes in the
ExtResponse is the base class that simply deals with the success and message properties. The message property is only serialized if if is not null, thanks to this Jackson JSON attribute:
The ExtData class extends this class and knows how to deal with the data and total properties. It provides a simple method to add data to an internal list and correctly calculate the total property. This simplifies the controller methods to look like this:
Technically, I only removed one like of code from the previous example, but using the ExtData abstraction makes the code easier to read and eliminates tracking down a hard-to-find error in case you mis-type the name of one of the properties.