October 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Real World REST Using Jersey, AJAX and JSON

  • October 9, 2009
  • By Bob Reselman
  • Send Email »
  • More Articles »

Setting the REST Entry Point

Notice please that in Listing 3 above we've set the entry point for REST URLs to be /rest/*. The line of code below shows an example of a REST entry point that conforms to the entry point configured in Listing 2.

http://localhost:9090/card-dealer-rest/rest/....

Where:
http://localhost:9090 is the domain
/card-dealer-rest/ is the web app
/rest/ is the REST entry point

We are directing REST traffic to /rest/* because we want to leave the root open so that the web server can process URLs for standard web traffic such as:

  http://localhost:9090/card-dealer-rest/hellow-world.html

  http://localhost:9090/card-dealer-rest/index.html

The benefit here is that we can setup our web app to be both a REST server and a web site that feeds usual web pages that use the REST Server. The reason for having both REST Server and the web pages share the same domain is that we'll be able to write AJAX call backs to the REST server and avoid the cross site security issue. AJAX does not allow you to make XmlHttpRequest calls into any site other than the originating site. Thus, having everything in the same site makes our REST services available to our web pages.

Defining the Card Images Directory

As mentioned above, CardDealer uses Spring injection to set the location of the card image directory in CardDealerHelper. Also, Spring injection is used to supply the filename of the empty card graphic. This information is part of the Spring context configuration file, as shown below in List 4.

Listing 4: A snippet from the web app file, spring-context.xml, for Spring configuration settings

<context:component-scan base-package="com.edmunds.fun.cards" />
<!--
  Inject cardDealerHelper with the information for
  imageDirectoryLocationFileSpec and emptyShoeImageFileSpec
-->
<bean id="cardDealerHelper" class="com.edmunds.fun.cards.CardDealerHelper">
  <property name="imageDirectoryLocationFileSpec" value="C:/Projects/CardGames/card-deck" />
  <property name="emptyShoeImageFileSpec" value="empty-shoe.jpg" />
</bean>

Getting the REST Server up and running using Jetty

The stage is now set to start the REST server. The Maven POM file for the project has been configured to use the Jetty Web Server. Jetty has set in the project to run as a Maven goal. So starting it up is a simple affair.

First we call the Maven install goal to compile, build and install artifacts in the local machine's repository as shown in Figure 5.

Maven Install
Figure 5: Use the Maven install goal to build the project
(click to view)

Then we change the directory down to the project web app and start up the Jetty server using man jetty:run as shown in Figure 6.

Maven Jetty Run
Figure 6: We'll use the Jetty server to get web pages and access REST services
(click to view)

If all is in order, you'll see the Jetty 'up and running" message in your terminal's window as shown below in Figure 7.

Up and Running
Figure 7:The project's web app runs on port 9090

Now were ready to work on the client-side.

Getting REST Application Information Using WADL

One of nicer features of Jersey is that you can configure it to display a WADL file that describes the REST services available on the server. WADL is an acronym for Web Application Description Language. WADL is an XML file that tells you, among other things, how the Java resource class binds to REST URLs. The CardDealerRest project POM file has configured the necessary artifacts which enables the automatic display. So, to view the WADL file for the project we enter the URL:

http://localhost:9090/card-dealer-rest/rest/application.wadl

The trick to getting the WADL file to display automatically is to provide a URL that has "application.wadl" directly after the entry point to the REST service. Figure 8 below shows the result of calling the WADL for the CardDealer REST Service.

Maven Jetty Run
Figure 8: Web Application Description Language (WADL) is an XML structure that is self describing
(click to view)

Calling a Rest Service Using Ajax

Now we're ready to get some cards via a web page. We call, http://localhost:9090/card-dealer-rest/index.html which is the page that has the client side card retrieval code. We click the Get Card button and a card appears. How? By way of AJAX.

The button's click event is bound to a JavaScript getCard() function. getCard() makes an AJAX call back to the REST Server. (Please see Listing 5.) The REST server sends back a string that describes a card as a JSON version of the RestCard object. RestCard is a facade object that presents the Card.imageBytes property as a Base64 encoded string.

Listing 5: The JavaScript function getCard() is called when the Get Card button is clicked.

function getCard()
  {
    if (window.XMLHttpRequest)
       {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
       }
     else if (window.ActiveXObject)
       {
         // code for IE6, IE5
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
     else
        {
          alert("Your browser does not support XMLHTTP!");
        }
     //get the card's shoeId, if one is in play
     var currentShoeId = document.getElementById("shoeId").value;
     //Prepare the REST URL 
     var URL = "rest/card-dealer/card?shoeId=" + currentShoeId;
     xmlhttp.open("GET",url,true);
     xmlhttp.onreadystatechange=callback;
     xmlhttp.send(null);
  }

The JSON-ized RestCard object publishes three properties, code, image and shoeId. The code property reports the suit and rank of the card using the card code convention described above. shoeId reports the particular shoe from which the card was dealt and the property. Image is a Base64 encoded string that contains a graphic of the playing card. Listing 6 below shows the an example of a JSON string that describes a playing card retrieved from the CardDealer REST service.

Listing 6: The JSON Card object publishes the properties, code, image, and shoeId where the property image is a Base64 encoding of a card graphic

{"code":"c12",
"fileFormat:"gif",
"image":"R0lGODlhUQB0ALMAAAAAAIAAAACAAICAAAAAgIAAgACAgICAgMDAwP8AAAD/AP//AAAA//8A/wD/\\r\\n/////yH5BAEAAAIALAAAAABRAHQAAAT+UMhJq7046827/2DoAWRpnmiqrmx7ZsAjz3Rt33iu7zVw\\r\\nxbygcEiU+SjAonK5PEqSzKg05xRAp1hs9ZrtNpEzlNcr7oGN5fE0ZZ5ASWiuWgl/lGhbfLI+j/L5\\r\\ndmdoYXJ9Q39vgnZ7hYZBiHiKkI5NjJFueoSUlZphkpabRZNGn3GhokB3nphxJqdEbJdPhK6vhyc2\\r\\neY8uvL2xPLrAC8PExQkkCXbKcI2PQsG0PQDF1McAycyLzaa50lzQ2oAx08UkC9bYg4A3uD16qquz\\r\\n7+JG5efoy0bKVGn6tOvQxmXzR45YAnTY3qybB8/fsoGkWIVrt8cYvn2ZcPwiqCKelX/+FMMsMGft\\r\\nmikTx/g15Pgr2AqH06YdRJauTomU3rTpZJkm4LhFYeoNm4kMJiGcrV5izCZOkQwHABy4s2MQIcal\\r\\n1xjxuvoAqtQ28t65i3nN6lWtOH1xXRlI4g5zI4maPGvz2MyJLLhScUplkdyDDnPNvItLoKptHhHD\\r\\nvJnMDtI7N2kaZhn0EV+N7xr73dMKoUI5ituGfUsL8KKR4lAjk5y0m2W3OlLR9HtupOqYCYaWXQ3s\\r\\n2WV22gCnyn3Qtszc58YRffzNN2yVWVMgP0jd4InBw63hcT46NjJiha9Ru/cTd1bHrAPH/p2LXMFU\\r\\ncUpqP23eMXWkejWy72Ev5kPlhJX+AB4i50HG3UeP3HfMgEwRV55x5lwxzoAHhlbWfe6htgx1AoFn\\r\\njY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TjBgfhPzcaUY5r9Ikb5ThHoNSRjn7kYx+bokZQCHJygLTgZxJ5\\r\\nSG4QsjsvbCQInwPGRm7xjaGxJPIyqclzea6T0gPlISrASVHKAlqm9AgpscjKVl5RBLCMpSxnScta\\r\\nxjICAAA7\\r\\n",
"shoeId":"0ad84189-0ba3-46c3-a082-63f9e561d87d"}


Tags: Web services



Page 3 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel