Bruno Raljić

A Java Developer's Blog

AJAX with Spring MVC

As I continued to explore the world of Spring MVC, I wondered how the AJAX calls are handled and I found it to be very simple. I’ll present you a simple example, including a little bit of jQuery, JSON, twitter4j etc.

Example description

Let’s say we want to display specific tweet on our page. User have input field and after providing the URL, tweet content will be displayed on the page. When I say content, I mean basic content (text, author, timestamp and author’s profile image), without any Twitter specific CSS or options (you can also get full tweet using OEmbed, but for this example let’s do it this way).

After providing URL we will:

  • bind some jQuery actions to trigger AJAX call,
  • extract tweet ID,
  • find specific tweet with twitter4j,
  • extract only needed fields,
  • convert it to JSON object and return with Spring MVC,
  • put the appropriate text/image back to the page.

Preparing the page

Add simple input field where users will provide the URL:

<input id="tweetUrl" type="text" />

After that, bind the following actions to this field:

$("#tweetUrl").bind("keyup change input", function() {

You may notice how I binded multiple actions “keyup change input”, so the AJAX call will be triggered if you press CTRL+V or click “Paste”. If I missed some action that could be used here, please leave a comment.

Now, let’s make some ajax request with jQuery:

$.post('retrieveTweet', {
    tweetUrl : inputUrl // value from input field
}, function(data) {
    // More details later

Server side

Now, as we provided the path “retrieveTweet”, we need to add a mapping in the Spring MVC controller.

public @ResponseBody
String retrieveTweet(@RequestParam("tweetUrl") String tweetUrl)
        throws TwitterException {
    long statusId = UrlUtil.extractIdFromUrl(tweetUrl);
    Status status = null;
    try {
        status = twitter.showStatus(statusId);
    } catch (Exception e) {
        // NOP
    return JsonUtil.getTweetForPreview(status);

You may notice two things:


which maps our request and

@ResponseBody String

which tells Spring that we are expecting this string to be a response (not actual view name). This is exactly what we need for our AJAX requests. And that’s it, nothing else. So whatever you return in this method, you can use it later on the client side as data.

The @ResponseBody annotation is similar to @RequestBody. This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name) documentation

For this example, I used twitter4j to retrieve the tweet. As this is not article about (configurating) twitter4j, I left out the details. Maybe you just want to know that the twitter is of type twitter4j.Twitter. I’ve also moved out the logic for extracting ID from the URL and extracting needed fields from actual tweet, to meet our needs. I’ll show you how I created JSON object.

public static String getTweetForPreview(Status tweet) {
    if (tweet == null) {
        return "{}";
    Map<String, String> mapJson = new HashMap<String, String>();
    mapJson.put("img", tweet.getUser().getProfileImageURL());
    mapJson.put("text", tweet.getText());
    mapJson.put("authorName", tweet.getUser().getName());
    mapJson.put("authorUsername", tweet.getUser().getScreenName());
    mapJson.put("timestamp", sdf.format(tweet.getCreatedAt()));

    JSONObject json = new JSONObject(mapJson);

    return json.toString();


As you can see, I choose constructor with Map, because I get better overview, and I chose only five elements out of much more. Now I have a JSON object which looks something like this:

 "timestamp":"03 jan 2013 07:59:55",
 "text":"#Webinar Today: Building your First App with #MongoDB",
 "authorName":"Bruno Raljić",
 "img": ""

Note: Link for img is broken, I cut few numbers in order to put it in this code block.

Client side, again

Now, when we have a String, representing JSON object, returned by Spring MVC, lets use it in jQuery, to set some values.

$.post('retrieveTweet', {
    tweetUrl : inputUrl
}, function(data) {
    var tweet = jQuery.parseJSON(data);
    $("#"+imgSelector).attr("src", tweet.img);


Using AJAX with Spring MVC is pretty simple. You just need to add a @ResponseBody annotation. I added few details to make this example interesting. When I searched for this on google, I found Ajax with Spring MVC 3 using Annotations and JQuery tutorial so you can check it out, too.

, , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Show my latest blog post with this comment!