20
JAX-RS (RESTful WS) M.C. Juan Carlos Olivares Rojas Julio 2011

JAX-RS (RESTful WS)

  • Upload
    mervyn

  • View
    60

  • Download
    0

Embed Size (px)

DESCRIPTION

JAX-RS (RESTful WS). M.C. Juan Carlos Olivares Rojas. Julio 2011. REST. Es un protocolo más sencillo de manejar los servicios Web, se caracteriza por no manejar SOAP ni WSDL y por lo tanto es más ligero. - PowerPoint PPT Presentation

Citation preview

Page 1: JAX-RS (RESTful WS)

JAX-RS (RESTful WS)

M.C. Juan Carlos Olivares Rojas

Julio 2011

Page 2: JAX-RS (RESTful WS)

REST

• Es un protocolo más sencillo de manejar los servicios Web, se caracteriza por no manejar SOAP ni WSDL y por lo tanto es más ligero.

• Los demás protocolos se siguen conservando. Los Servidores Web deben soportar este tipo de Servicios (ya es muy común)

Page 3: JAX-RS (RESTful WS)

JAX-RS

• REST (Representational State Transfer)

• Muchos Servicios Web de la Web 2.0 trabajan bajo este enfoque.

• REST está orientado a los recursos.

• Utiliza los métodos GET, POST, PUT y DELETE de HTTP.

Page 4: JAX-RS (RESTful WS)

JAX-RS

• Es la API de java para crear Servicios Web basados en la arquitectura REST

• Al igual que JAX-WS utiliza anotaciones como: @Path, @GET, @PUT, @DELETE, @HEAD, entre otras.

Page 5: JAX-RS (RESTful WS)

JAX-RS

• La implementación mejor conocida de JAX-RS se denomina Jersey.

• Existe un mapeo entre las acciones a realizar y el verbo.

Acciones Verbo

Create POST

Retrieve GET

Update PUT

Delete DELETE

Page 6: JAX-RS (RESTful WS)

JAX-RS

• La descripción de los WS con REST se hace a través de WADL (Web Appliction Description Language), el cual es un archivo basado en XML que contiene las operaciones disponibles y su forma de acceso a través del protocolo HTTP.

Page 7: JAX-RS (RESTful WS)

Ejemplo 1: SOAPPOST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn

<?xml version="1.0"?> <soap:Envelope

xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock">

<m:GetStockPrice> <m:StockName>IBM</m:StockName>

</m:GetStockPrice> </soap:Body>

</soap:Envelope>

Page 8: JAX-RS (RESTful WS)

Ejemplo 1: REST

GET /stock/IBM HTTP/1.1 Host: www.example.org Accept: application/xml

Page 9: JAX-RS (RESTful WS)

Ejemplo 2: SOAPPOST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn

<?xml version="1.0"?> <soap:Envelope

xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock">

<m:BuyStock> <m:StockName>IBM</m:StockName> <m:Quantity>50</m:Quantity>

</m:BuyStock> </soap:Body>

</soap:Envelope>

Page 10: JAX-RS (RESTful WS)

Ejemplo 2: RESTPOST /order HTTP/1.1 Host: www.example.org Content-Type: application/xml;

charset=utf-8

<?xml version="1.0"?> <order>

<StockName>IBM</StockName><Quantity>50</Quantity>

</order>

Page 11: JAX-RS (RESTful WS)

Acceso a los Recursos

• Create– POST /resourceName

• Retrieve– GET /resourceName/resourceId

• Update– PUT /resourceName/resourceId

• Delete– DELETE /resourceName/resourceId

Page 12: JAX-RS (RESTful WS)

Hola Mundo!!!import javax.ws.rs.Path;

import javax.ws.rs.GET;

import javax.ws.rs.ProduceMime;

@Path("/helloRest")

public class HelloRest {

@GET

@ProduceMime("text/html")

public String sayHello() {

return "<html><body><h1>Hello from Jersey!</body></h1></html>";

}

}

Page 13: JAX-RS (RESTful WS)

HolaMundo!!!

• Este servicio Web se ejecuta simplemente colocando la URL en el navegador.

• Si se ocupan pasar parámetros, dichos parámetros se pasan a través de la URI por medio de los verbos HTTP.

Page 14: JAX-RS (RESTful WS)

Ejemplo de Parametros en URI@Path("/products/{id}")public class ProductResource {

@Contextprivate UriInfo context;/** Creates a new instance of ProductResource */public ProductResource() { }

@GET@ProduceMime("text/plain")public String getProduct(@PathParam("id") int productId)

{switch (productId) {case 1: return "A Shiny New Bike";case 2: return "Big Wheel";case 3: return "Taser: Toddler Edition";default: return "No such product";

}}

}

Page 15: JAX-RS (RESTful WS)

Expresiones Regulares

• Como puede observarse, las direcciones de los servicios Web pueden manejar expresiones regulares para simplificar mejor su uso.

• También se puede indicar el verbo de ejecución del WS.

Page 16: JAX-RS (RESTful WS)

Parámetros de @Path

@Path(“customer/{name}")public class Customer {

@GETString get(@PathParam("name") String name) { … }

@PUTVoid put(@PathParam(“name”) String name, String value) { … }

Page 17: JAX-RS (RESTful WS)

Ejemplo Expresiones Regulares

@Path("/products/{id: \\d{3}}")public class ProductResource {

public ProductResource() { }@GET@Produces("text/plain")public String

getProductPlainText(@PathParam("id") int productId) {

return "Your Product is: " + productId;}

}

Correcto:http://localhost:8080/jrs/resources/products/555 Incorrecto (regresa estado 404)http://localhost:8080/jrs/resources/products/7

Page 18: JAX-RS (RESTful WS)

Utilizando Cadenas de Búsqueda

@GET@Produces("text/xml")public String getProducts(

@PathParam("id") int productId,@QueryParam("results")@DefaultValue("5") int numResults)

• //…/resources/products?results=3

Page 19: JAX-RS (RESTful WS)

Acceso a Encabezados

@GET public String doGet(@Context HttpHeaders headers) {

//list all incoming headersMultivaluedMap<String,String> h = headers.getRequestHeaders();

for (String header : h.keySet()) {System.out.println(header + "=" + h.get(header));

}

Page 20: JAX-RS (RESTful WS)

Du

das