Sie sind auf Seite 1von 18

Chapitre 5.

Les frameworks REST

Chapitre 5

Les Frameworks REST

Les frameworks REST

Sommaire
Qu'est ce que REST ?
Le format JSON
Mise en uvre de REST avec JAX-RS et Jersey
Mise en uvre de REST avec Apache-CXF
Mise en uvre de REST avec REST-Easy de JBoss
Mise en uvre de REST avec Spring MVC

M.Romdhani, INSAT, Dcembre 2015

Chapitre 5. Les frameworks REST

Qu'est ce que REST ?

Les frameworks REST

Qu'est ce que REST?


"The motivation for developing REST was to create
an architectural model for how the Web should work,
such that it could serve as the guiding framework
for the Web protocol standards
Roy Fielding
REST (Representational state transfer) est une manire de construire une
application pour les systmes distribus comme le Web. Le terme a t invent
par Roy Fielding en 2000.
REST n'est ni un protocole ni un format, c'est un style darchitecture, bti sur
quelques principes simples :
L'URI est fondamentale : connatre l'URI doit suffire pour accder la ressource ;
HTTP fournit toutes les oprations ncessaires (GET, POST, PUT et DELETE,
essentiellement) ;
Chaque opration est auto-suffisante : il n'y a pas d'tat ;
Utilisation des standards hypermedia : HTML ou XML qui permettent de faire des
liens vers d'autres ressources et d'assurer ainsi la navigation dans l'application
REST.

M.Romdhani, INSAT, Dcembre 2015

Chapitre 5. Les frameworks REST

Les frameworks REST

Architecture oriente ressource


Linformation de base, dans une architecture REST, est appele
ressource. Dans un systme hypermedia, une ressource est tout ce qui
peut tre rfrenc par un lien.
Une ressource est identifie par un identificateur de ressource. Sur le
web ces identificateurs sont les URI (Uniform Resource Identifier).
Enfin, les composants de larchitecture manipulent ces ressources en
transfrant des reprsentations de ces ressources ( format HTML ou
XML).

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Architecture oriente ressource

M.Romdhani, INSAT, Dcembre 2015

Chapitre 5. Les frameworks REST

Les frameworks REST

REST et le Web
REST est le style architectural original du Web !
Tous les services Web que nous utilisons depuis des annes ,services
de commande des livres , services de recherche ,dictionnaire en ligne
sont des Web services bass sur REST.
Donc, vous tes entrain dutiliser REST sans le savoir !

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Pourquoi lappellation Representational state


transfer?
http://www.boeing.com/aircraft/747
Resource

Client
Fuel ncessaire
Maintenance prvue
.

Boeing747.html
Le client rfrencie une ressource Web grace une URL.Il reoit une
reprsentation de la ressource(ici un doc HTML).
La nouvelle reprsentation (Boeing747.html) place lapplication cliente
dans un autre tat(state).
Ainsi, lapplication cliente change(transfers) dtat avec chaque
reprsentation

M.Romdhani, INSAT, Dcembre 2015

Chapitre 5. Les frameworks REST

Les frameworks REST

Caractristiques du modle REST


Client-Server:
La sparation des concepts amliore la portabilit de l'interface
utilisateur travers les diverses plates-formes.
Permettre aux composants d'voluer indpendamment.
Stateless: (sans tat)
L'tat de la session est entirement dtenu par le client.
La fiabilit est amliore car il est plus simple de faire face des checs
partiels (restauration)
La possibilit de monte en charge est meilleure.
Cache:
Offre la possibilit dliminer tout ou une partie de certaines interactions
Amliore l'efficacit, la monte en charge et rduit la latence moyenne
dans une srie d'interactions.

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Caractristiques du modle REST


Uniform interface:
Toutes les ressouces sont manipules par une interface gnrique
(HTTP GET, POST, PUT, DELETE).

Code la demande:
REST permet lextension des fonctionnalits dun client en tlchargeant et excutant
du code sous forme d'applet ou de scripts.
Amliore l'extensibilit du systme grce la possibilit de tlcharger des
fonctionnalits aprs le dploiement.

M.Romdhani, INSAT, Dcembre 2015

10

Chapitre 5. Les frameworks REST

Les frameworks REST

REST et les web services


Un web service qui suit larchitecture REST est dit RESTful
Le web doit son succs ce style darchitecture oriente ressource. Il
na pas t conu comme un BUS XML pour transfrer des messages
entre applications (cas du SOAP).
Les qualits recherches pour le web rejoignent celles des web
services : sparation des tches, simplicit, interoprabilit,
performances rseaux, ...

11

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

REST Web-services
HTTP methods
GET defines a reading access of the resource without side-effects. The
resource is never changed via a GET request, e.g. the request has no
side effects (idempotent).
PUT creates a new resource, must also be idempotent.
DELETE removes the resources. The operations are idempotent, they
can get repeated without leading to different results.
POST updates an existing resource or creates a new resource.

M.Romdhani, INSAT, Dcembre 2015

12

Chapitre 5. Les frameworks REST

Les frameworks REST

REST Web-services
Example
base URI for the web service: http://example.com/resources/
Resource

GET

PUT

POST

DELETE

Collection URI, such as


http://example.com/resourc
es/

List the URIs and


perhaps other details
of the collection's
members.

Replace the entire


collection with
another collection.

Create a new entry


in the collection.
The new entry's
URL is assigned
automatically and
is usually returned
by the operation.

Delete the entire


collection.

Element URI, such as


http://example.com/resourc
es/item17

Retrieve a
representation of the
addressed member of
the collection,
expressed in an
appropriate Internet
media type.

Replace the
addressed member
of the collection, or
if it doesn't
exist, create it.

Not generally used.


Treat the addressed
member as a
collection in its
own right
and create a new
entry in it.

Delete the
addressed
member of the
collection.

13

M.Romdhani, INSAT, Dcembre 2015

Le format JSON

Chapitre 5. Les frameworks REST

Les frameworks REST

JSON Notation
A lightweight data-interchange format
A subset of the object literal notation of JavaScript (or ECMA-262).
A JSON string must be enclosed by double quotes.
Comparison of JSON and XML
Similarities:
Both are human readable/Both have very simple syntax
Both are hierarchical/Both are language independent
Both can be used by Ajax

Differences:
Syntax is different
JSON is less verbose
JSON includes arrays
Names in JSON must not be JavaScript reserved words
XML can be validated
JavaScript is not typically used on the server side
15

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

JSON example
JSON stands for JavaScript Object Notation
Despite the name, JSON is a (mostly) language-independent way of specifying
objects as name-value pairs
Example (http://secretgeek.net/json_3mins.asp):
{"skillz": {
"web":[
{ "name": "html",
"years": 5
},
{ "name": "css",
"years": 3
}]
"database":[
{ "name": "sql",
"years": 7
}]
}}

M.Romdhani, INSAT, Dcembre 2015

16

Chapitre 5. Les frameworks REST

Les frameworks REST

JSON syntax, I
An object is an unordered set of name/value pairs
The pairs are enclosed within braces, { }
There is a colon between the name and the value
Pairs are separated by commas
Example: { "name": "html", "years": 5 }
An array is an ordered collection of values
The values are enclosed within brackets, [ ]
Values are separated by commas
Example: [ "html", xml", "css" ]

17

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

JSON syntax, II
A value can be: A string, a number, true, false, null, an object, or an
array
Values can be nested
Strings are enclosed in double quotes, and can contain the usual
assortment of escaped characters
Numbers have the usual C/C++/Java syntax, including exponential (E)
notation
All numbers are decimal--no octal or hexadecimal
Whitespace can be used between any pair of tokens

M.Romdhani, INSAT, Dcembre 2015

18

Chapitre 5. Les frameworks REST

Les frameworks REST

Using JSON in JavaScript


JSON encoded data

JavaScript object

var myObject = Eval('(' + myJSONtext + ')');


var myObject = JSON.Parse(myJSONtext);

JavaScript value

JSON encoded data

var myJSONText = JSON.stringify(myObject);

19

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Using JSON with XmlHttpRequest


Sending JSON encoded data to the server
Use HTTP POST method and send the JSON encoded data in the body of
the request
// xmlhttp is an XmlHttpRequest object
xmlhttp.setRequestHeader(
'Content-type',
'application/x-www-form-urlencoded;charset=UTF-8;'
);
xmlhttp.send('jsondata=' + escape(myJSONText));

Handling JSON encoded data from the server


Server should set the content type to "text/plain"
In the handler function of xmlhttp object, read xmlhttp.responseText

M.Romdhani, INSAT, Dcembre 2015

20

10

Chapitre 5. Les frameworks REST

Mise en uvre de REST


avec JAX-RS et Jersey

Les frameworks REST

JAX-RS
JSR-311: JAX-RS: The Java API for RESTful Web Services
Introduced in Java SE 5: annotation-based
Objective: simplify the development and deployment of web
service clients and endpoints.
Part of Java EE 6
No configuration is necessary to start using JAX-RS

M.Romdhani, INSAT, Dcembre 2015

22

11

Chapitre 5. Les frameworks REST

Les frameworks REST

JAX-RS API
Specifications
Annotations to aid in mapping a resource class (a Plain Old
Java Object) as a web resource.
@Path specifies the relative path for a resource class or method.
@GET, @PUT, @POST, @DELETE and @HEAD specify the HTTP request type of a
resource.
@Produces specifies the response MIME media types.
@Consumes specifies the accepted request media types.

Annotations to method parameters to pull information out of the


request. All the @*Param annotations take a key of some form
which is used to look up the value required.
@PathParam binds the parameter to a path segment.
@QueryParam binds the parameter to the value of an HTTP query parameter.
@MatrixParam binds the parameter to the value of an HTTP matrix parameter.
@HeaderParam binds the parameter to an HTTP header value.
@CookieParam binds the parameter to a cookie value.
@FormParam binds the parameter to a form value.
@DefaultValue specifies a default value for the above bindings when the key is not
found.
@Context returns the entire context of the object. Ex.(@Context HttpServletRequest
request)
M.Romdhani, INSAT, Dcembre 2015

23

Les frameworks REST

JAX-RS API

M.Romdhani, INSAT, Dcembre 2015

24

12

Chapitre 5. Les frameworks REST

Les frameworks REST

JAX-RS implementations
Implementations
Jersey, from Sun/Oracle (Java EE 6 reference implementation)
Apache, CFX from Apache
RESTeasy, from JBoss
Restlet, created by Jerome Louvel, a pioneer in REST frameworks.

25

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Jersey
Jersey is the reference implementation for the JSR 311 specification.
The Jersey implementation provides a library to implement Restful
webservices in a Java servlet container.
On the server side Jersey provides a servlet implementation which
scans predefined classes to identify RESTful resources.
In your web.xml configuration file your register this servlet for your web
application.
The Jersey implementation also provides a client library to communicate
with a RESTful webservice.
JAX-RS supports the creation of XML and JSON via the Java
Architecture for XML Binding (JAXB).

M.Romdhani, INSAT, Dcembre 2015

26

13

Chapitre 5. Les frameworks REST

Les frameworks REST

Mise en uvre de REST avec Jersey


Steps
Setup of Jersey libraries either manually or using a depedency
management tools like Maven or Gradle
Create a web application and register the Jersey Servlet dispatcher
in web.xml
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. ->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.vogella.jersey.first</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Develop the Web Service using the JAX-RS Annotations


Run the service

27

M.Romdhani, INSAT, Dcembre 2015

Mise en uvre de REST


avec Apache-CXF

14

Chapitre 5. Les frameworks REST

Les frameworks REST

Mise en uvre de REST Apache-CXF


Steps
Create the Web App using Maven and download the Apache CXF
dependencies
Configure Apache CXF in the Web App
<<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listenerclass>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/rest-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Contd

29

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Mise en uvre de REST Apache-CXF


Step (contd)
Configure the rest-servlet.xml
<cxf:bus>
<cxf:features>
<cxf:logging/>
</cxf:features>
</cxf:bus>
<bean id="accountService" class="server.service.AccountService" initmethod="init"></bean>
<bean id="jsonProvider"
class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
<jaxrs:server id="accountrs" address="/rservice">
<jaxrs:serviceBeans>
<ref bean="accountService"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean='jsonProvider' />
</jaxrs:providers>
</jaxrs:server>

Create the Service Implementation on the App


Test out the service

M.Romdhani, INSAT, Dcembre 2015

30

15

Chapitre 5. Les frameworks REST

Mise en uvre de REST


avec REST-Easy

Les frameworks REST

Mise en uvre de REST Easy


Steps
Create the Web App using Maven and download the Apache CXF
dependencies
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>

Configure Apache CXF in the Web App


<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Contd
M.Romdhani, INSAT, Dcembre 2015

32

16

Chapitre 5. Les frameworks REST

Les frameworks REST

Mise en uvre de REST Easy


Steps (Contd)
Create the Web App using Maven and download the Apache CXF
dependencies
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>

Configure Apache CXF in the Web App


<listener><listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap </listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Create the Service Implementation on the App


Test out the service

33

M.Romdhani, INSAT, Dcembre 2015

Mise en uvre de REST


avec Spring MVC

17

Chapitre 5. Les frameworks REST

Les frameworks REST

Mise en uvre de REST avec Spring MVC


Spring MVC 4 annotations supporting REST
@RestController : Spring 4s new @RestController annotation. This annotation eliminates the
need of annotating each method with @ResponseBody. Under the hood, @RestController is
itself annotated with @ResponseBody, and can be considered as combination of @Controller
and @ResponseBody.
@RequestBody : If a method parameter is annotated with @RequestBody, Spring will bind the
incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to
that parameter. While doing that, Spring will [behind the scenes] use HTTP Message converters
to convert the HTTP request body into domain object [deserialize request body to domain
object], based on ACCEPT or Content-Type header present in request.
@ResponseBody : If a method is annotated with @ResponseBody, Spring will bind the return
value to outgoing HTTP response body. While doing that, Spring will [behind the scenes] use
HTTP Message converters to convert the return value to HTTP response body [serialize the
object to response body], based on Content-Type present in request HTTP header. As already
mentioned, in Spring 4, you may stop using this annotation.
ResponseEntity is a real deal. It represents the entire HTTP response. Good thing about it is
that you can control anything that goes into it. You can specify status code, headers, and body.
It comes with several constructors to carry the information you want to sent in HTTP Response.
@PathVariable This annotation indicates that a method parameter should be bound to a URI
template variable [the one in '{}'].
Basically, @RestController , @RequestBody, ResponseEntity & @PathVariable are all you need to
know to implement a REST API in Spring 4. Additionally, spring provides several support classes to
help you implement something customized.
35

M.Romdhani, INSAT, Dcembre 2015

Les frameworks REST

Mise en uvre de REST avec Spring MVC


Steps
Create the Web App using Maven and download the Spring mvc
dependencies
Configure the dispatcher servlet in the Web App
Create the Service Implementation on the App
Test out the service

M.Romdhani, INSAT, Dcembre 2015

36

18

Das könnte Ihnen auch gefallen