restful application development...beginning with jersey • to begin using jersey, drop the...
TRANSCRIPT
Restful Application Development
Instructor WelcomeCurrently a consultant in my own business and splitting my time between training and consulting.
Assist clients to incorporate Web 2.0 technologies and solutions to enhance collaboration and rich application development.
Proponent of developing standards-based solutions and layered semantic architectures.
Introduced developers within Yahoo to the Yahoo User Interface (YUI) Library.
Have extensive experience with Prototype, jQuery, ExtJS, and Dojo as well.
Authored numerous Web 2.0-based courses, including those on developing Rich Internet Applications.
Rob Gance
Today's Agenda• Rest Architectures
– Advantages of REST– Java Solutions using REST– Java-based REST Frameworks
• Implementing with REST– Creating and Manipulating REST-based Services– Binding Web Services with the Front-End
REST Architectures
RESTful Web Services
• REST– Representational State Transfer
– A distributed architecture often associated with Service-Oriented Architectures
– A set of principals that define how resources are accessed and manipulated
Motivations for REST• REST is a data-centric view of services
– Follows the intended vision for the way information should be exchanged on the web
– Semantic use of HTTP methods
• Ease of use in RIAs, front-end architectures– Lends itself toward "Web 2.0" implementations– Plays well with browsers
Resistance to REST
• SOA (SOAP, WSDL, etc.) has huge industry backing– Pushed heavily by large IT companies
• How can REST cover all of the complexities of "real" applications?
Naming Resources• REST uses globally unique identifiers
• Examples of Resources:– Blog entries– Queries– Calculations– Published Documents or Files
URI Resource
Examples of using URLs
http://my.server.com/RestApp/country/Canada
http://my.server.com/RestApp/country/France/capital
http://my.server.com/RestApp/country/France/city/Paris
http://my.server.com/RestApp/country
http://my.server.com/RestApp/dept
http://my.server.com/RestApp/dept/HR/employee
http://my.server.com/RestApp/dept/HR/employee/2341
http://my.server.com/RestApp/dept/HR
REST URLs vs. Query Strings
• Careful, not all URLs are RESTful:
http://my.server.com/getemployee&id=12345677
– Doesn't map nicely to all the rest actions– An update would require changing the URL
http://my.server.com/getemployee&id=12345677
Works best as a nounWorks best as a noun
REST Verbs
• There are four HTTP behaviors associated with REST actions
– GET
– DELETE
– PUT
– POST
GET• The GET operation performs a read
– It is considered a "safe" operation
– Nothing on the server-side changes
– GET can return complete representations or partial ones
• Makes it suitable for query operations
GET http://my.server.com/ReadApp/country/France
DELETE
• DELETE removes a resource
• It is not commonly implemented for all resources
DELETE http://my.server.com/ReadApp/employee/2341/address
DELETE http://my.server.com/ReadApp/country
This could have disastrous effects if allowedSome clients, such as Flex and
Silverlight, cannot properly handle DELETE and PUT operations
Some clients, such as Flex and Silverlight, cannot properly handle DELETE and PUT operations
PUT• PUT replaces or creates a specified
resource
– Similar to a DB insert or delete and then insert
• While POST is often used to create server-side resources, strictly speaking, a PUT operation is most suited for this task
POST
• POST can be used to create or modify a resource
– Semantically, using a POST to retrieve a resource's state is not correct
• POST should generally be used to updatethe state of a resource
Example Representation
• A blog entry
{ "title" : "The London Eye", "created" : "17-Feb-09","user" : "Ed Rice" }
Blog EntryTitle
DateCreatedUsernameComments
Blog EntryTitle
DateCreatedUsernameComments
ClientClient
Java and REST
• Java has defined JAX-RS (JSR 311) as the Java API for RESTful Web Services
– 1.0 release, Sept. 2008
– Available separately now (via Jersey)
– Will become incorporated into Java EE 6
https://jsr311.dev.java.net/https://jsr311.dev.java.net/
A Survey of REST Implementations
• A number of Java-based REST-oriented frameworks exist:
– Jersey
– Restlets
– RESTEasy
– CXF
https://jersey.dev.java.net
http://www.restlet.org
http://cxf.apache.org
http://www.jboss.org/resteasy
CXF• Apache Project
– An open source Enterprise Service Bus• Supports other transports such as SOAP, CORBA,
XML over HTTP
– Its JAX-RS implementation can be used separately from the bus
– Integration with Spring– JSON binding– Full WS-* stack support
RESTEasy
• JBoss Implementation for JAX-RS
– Has built-in client-side framework
– Embeddable server for unit testing
– Support for Spring, Comet
Restlets
• Oldest of frameworks compared
• No support for annotations
Jersey
• JAX-RS Reference Implementation
– A few JARs to deploy into any servletcontainer
– Jersey 1.02 implements JAX-RS 1.0
Beginning with Jersey
• To begin using Jersey, drop the following JARs into your web application
– These are found in the Jersey distribution's lib directory
asm-3.1.jarjersey-core-1.0.2.jarjersey-server-1.0.2.jarjsr311-api-1.0.jar
asm-3.1.jarjersey-core-1.0.2.jarjersey-server-1.0.2.jarjsr311-api-1.0.jar
Create the Web App
• Create a typical web application
Our REST-based resource
Our REST-based resource
Web app config fileWeb app config file
Configure the Jersey Servlet
• A Servlet will be used to intercept requests
<servlet><servlet-name>JerseyServlet</servlet-name><servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class><load-on-startup>1</load-on-startup>
</servlet><servlet-mapping>
<servlet-name>JerseyServlet</servlet-name><url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet><servlet-name>JerseyServlet</servlet-name><servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class><load-on-startup>1</load-on-startup>
</servlet><servlet-mapping>
<servlet-name>JerseyServlet</servlet-name><url-pattern>/*</url-pattern>
</servlet-mapping>
web.xml
Create the Resource• The following resource was created nextpackage com.rest.demo;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;
@Path("/message")public class Message {
@GET@Produces("text/plain")public String getMessage() {
return "This is your typical hello world app!";}
}
package com.rest.demo;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;
@Path("/message")public class Message {
@GET@Produces("text/plain")public String getMessage() {
return "This is your typical hello world app!";}
}
JAX-RS annotations
JAX-RS annotations
Test It Out!
• That's it! Deploy the app and test it out!
• Browse to the following URL:
http://localhost:8080/RestApp/message
This is your typical hello world app!
Round Two• In this example we'll map to a list of
Country resources
http://localhost:8080/RestApp/country
Since no specific country indicated, refers to all countries
Since no specific country indicated, refers to all countries
The Resource
@Path("/country") public class CountryResource {
@GET@Produces("text/json")public String getCountries() {String retVal = "{'countries' : [ ";
for (int i = 0; i < ApplicationData.countries.size(); i++) {
// iterate over the countries, // build JSON output manually
}retVal += " ]}";
return retVal;}
}
@Path("/country") public class CountryResource {
@GET@Produces("text/json")public String getCountries() {String retVal = "{'countries' : [ ";
for (int i = 0; i < ApplicationData.countries.size(); i++) {
// iterate over the countries, // build JSON output manually
}retVal += " ]}";
return retVal;}
}
Output specified in JSON format
Output specified in JSON format
Developer must still define what is returned from methods
Developer must still define what is returned from methods
The Results
{'countries' : [ 'United States', 'Afghanistan', 'Argentina', 'Australia', 'Belgium', 'Brazil', 'Bulgaria', 'Cambodia', 'Canada', 'Cuba', 'Denmark', 'England', 'France' ]}
{'countries' : [ 'United States', 'Afghanistan', 'Argentina', 'Australia', 'Belgium', 'Brazil', 'Bulgaria', 'Cambodia', 'Canada', 'Cuba', 'Denmark', 'England', 'France' ]}
The representation is rendered in JSON format
The representation is rendered in JSON format
Okay, now what?• So far, we've introduced REST using JAX-
RS and the RI called Jersey
• Next we'll add: – Support for JSON output– Support for other REST actions
(PUT, DELETE, POST)
– Specify URLs for nested resources
– A Rich Ajax-based Front-End
Implementing with REST
Nested Path Parameters
• Let's add the ability to select individual countries– Recall the URL:
– Our solution requires a new path level and therefore a new Java resource
• CountryDetailsResource
GET http://localhost:8080/RestApp/country/Canada
CountryDetailsResource
@Path("/country/{name:[a-zA-Z]+}") public class CountryDetailsResource {
@GET@Produces("text/plain")public String getCountry(@PathParam("name")
String name) {
for (Country country : ApplicationData.countries) {if (country.getName().equalsIgnoreCase(name))return country.toString();
}
return new Country().toString(); // empty object }
}
@Path("/country/{name:[a-zA-Z]+}") public class CountryDetailsResource {
@GET@Produces("text/plain")public String getCountry(@PathParam("name")
String name) {
for (Country country : ApplicationData.countries) {if (country.getName().equalsIgnoreCase(name))return country.toString();
}
return new Country().toString(); // empty object }
}
Support for Path Parameters
Support for Path Parameters
JAX-RS Annotations
• The following is a list of some of the more common annotations in the javax.ws.rspackage
@Path@GET@POST@PUT@DELETE@PathParam@QueryParam@Produces@Consumes
Jersey and JSON
• Jersey supports the ability to convert Java objects to JSON using JAXB
• First some minor configuration additions:– Add the jersey-json.1.0.2.jar archive to the
project's /WEB-INF/lib directory
Binding JSON to Java@Path("/messageJSON")@XmlRootElement(name = "message")public class MessageJSON {
private String msg = "This is the default msg";
@GET@Produces("application/json")public MessageJSON getMessage(@QueryParam("msg")
String msg) {
this.msg = msg;
return this;}
}
@Path("/messageJSON")@XmlRootElement(name = "message")public class MessageJSON {
private String msg = "This is the default msg";
@GET@Produces("application/json")public MessageJSON getMessage(@QueryParam("msg")
String msg) {
this.msg = msg;
return this;}
}
GET http://localhost:8080/RestApp/messageJSON?msg=sample%20message
Using Other REST Actions
• POST Operation can be used to update country data
• DELETE could be used to remove a country
• PUT could be used to create/add a country
Creating a Client Front-End
• In the following example we'll add Ajax capability and RIA components using a JavaScript Library called ExtJS
• Other Libraries are possible: YUI, Dojo, jQuery, Prototype
Let's break it down...
The Front End Environment
• The Front End Uses ExtJS Components
Summary• In Today's Session we:
– Explored REST principles
– Discussed Various Java-based REST Frameworks
– Examined JAX-RS and Jersey
– Created an Ajax-based REST-oriented application using a JS Library, JAX-RS, and Jersey