Saturday, July 05, 2014

Spring Controllers as JSON API

[This is a post dated June 9, 2013 from my old wordpress blog]

I am currently working on a couple of projects which are single page web applications, where the clients interacts with spring controllers using JSON. Also, in one project we have a wordpress plugin which interacts with our controllers from wordpress sites.

Thought to summarize what all I needed to get this working.

First, let’s look at an example controller method:

The object returned by the method is converted to JSON by Jackson object mapper. For this to work, you have to have an ObjectMapper in your application context. To have it, first include it in your project. That means having this in your pom file, assuming you are using maven:

Then, create an object in your application context. If you are using Java configuration, this should do:

Instead of simlple form fields, request-params or path-variables, sometimes you might need to receive complex JSON data from the client. For that, the client code would look like:

and the controller code like this:

You have to define a SomeClass with fields corresponding to the structure of the data being received.

Finally, if you are switching between http and https protocols, or using your JSON API from a different place, as we do from our wordpress plugin, you will have to circumvent the Javascript Same Origin Policy. For that, I use CORS, or the cors-filter to be specific. To use that, include the following in your pom:

And, have this in your web.xml:

At the client side, my ajax setup, called before any ajax call is made, looks like this:

Please let me know your comments! Hope this would be useful as a quick reference to some (including me) in future.

No comments:

Post a Comment