Driving Sling with jQuery
From my first blog, oslutions.com (2005 to 2008), recovered from the Internet Archive and republished as it was. Links are from that time and many no longer work. Original: http://oslutions.com/blog/2008/09/driving-sling-with-jquery/.
Sling is a web framework that uses a Java Content Repository (JCR) to store and manage content. Sling is a project of the Apache Software Foundation (currently in the Incubator). As Lars puts it, “the main role of Sling is being a translator between the JCR repository and the client application.”
I’ve been experimenting with it for the last couple of days, and Sling is the coolest thing since I tried Ruby on Rails! Bye bye XML configurexageration and endless boilerplate code. Sling comes with the very handy SlingPostServlet that lets you do almost everything.
What’s the point?
Sling lets you drive your content repository from within a webpage by making an ajax request with jQuery. And it’s easy.
How do we get started?
There’s an excellent “15 minutes” Sling tutorial to get you started. For the example below, I used Day’s new CRX, a packaged and enhanced version of the Sling framework. You should definitively check it out, even if you don’t need a new computer…
- first, download and install CRX
- then start the server (on *nix: cd server, ./start) and check the welcome page: http://localhost:7402
- mount the jcr repository on your Desktop with WebDAV
- now create your sample application: from your WebDAV drive, create a folder “helloJquery” inside “apps”
- download jQuery and copy it in your “helloJquery” folder
- donwload this file and copy it in your “helloJquery” folder
- open your browser at http://localhost:7402/apps/helloJquery/helloJquery.html. the next steps are there…
What just happened?
We used jQuery to create a node named “mynode” below “content”, with a property “oneProperty” and value “oneValue”.
$.post(
"/content/*",
{ ':nameHint': 'myName', oneProperty: 'oneValue' },
function(data){ alert(data); }
);
If you are not familiar with jQuery, the code might look cryptic, but in 2 words: $.post creates the ajax post request, taking 3 parameters:
- “/content/*” as url, using SlingPostServlet to create a new jcr node under the /content node
- { ‘:nameHint’: “mynode”, oneProperty: ‘oneValue’ } is a key:pair list of request parameters. ‘:nameHint’ is a command (starts with ‘:’) that tells Sling to use “mynode” for the node name. oneProperty: sets one property under mynode
- the third (optional) parameter is a callback
It’s the ajax equivalent of using this html form:
<form action="/content/*" method="POST">
<input type="hidden" name=":nameHint" value=""myName">
<input type="text" name="oneProperty" value="oneValue">
</form>