JSONP in Grails Using Nothing But a Filter

Grails is a great platform for creating RESTful APIs. It comes with object serialization and formatting for XML and JSON out of the box, and it’s pretty easy to make your own custom builder if you decide you need some additional power.

One (at least in my mind) obvious use for a RESTful API would be calls from a third party (read: outside your application) JavaScript client using XMLHttpRequest (sometimes called AJAX). The current somewhat kludgey method to achieve this from the client is JSONP.

JSONP relies on a callback parameter which automatically formats the resulting JSON from the API. Just about every example of enabling JSONP in a Grails application I could find on Google and Stack Overflow was similar to

render "${params.jsoncallback}(${user as JSON})"

which meant it had to be in every controller that used it (somehow).

I wanted to enable JSONP across a bunch of existing controllers in my application and I decided a good way to do this would be a Grails filter. To do this in a Grails filter, you have to decide not to render your result from the controller (which isn’t necessarily a bad thing) and simply return it. An example:

def filters = {
   all(controller: '(jsonController1|jsonController2)', action: '*') {
     before = {

     after = { model ->
       String resp = model as JSON
       if(params.callback) {
         resp = params.callback + "(" + resp + ")"
       render (contentType: "application/json", text: resp)
     afterView = {

This example is relatively simple and assumes that everything is coming back as JSON and that any call with the callback parameter is JSONP. However, it should be an easy starting point to create more sophistication if necessary.


About johnnywey

Welcome to A Regular Expression. This blog is designed to reflect my thoughts on life, music, software design, Apple, faith, philosophy, and whatever else I can think of.

Posted on November 14, 2010, in Grails, Java, Programming. Bookmark the permalink. 2 Comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: