Post on 15-Jan-2015
description
Servicios RESTBases de la tecnología con
Spring MVC
José Ramón Berenguer Ana María Gómez
¿Qué es REST?
¿Por qué REST?
WSDL UDDI
SOAP
• Verbose• Complejidad• Alta curva de aprendizaje• Dificil de mantener• Alto consumo de recursos• No optimizado para web
REST(CATE) Representational State Transfer
Roy Fielding , 2000
• Sencillez• Eficiencia• Aprovecha características de la infraestructura Web
Técnica de arquitectura software para sistemas hipermedia distribuidos como
la Word Wide Web
Principios REST
• Protocolo cliente/servidor sin estadoCada mensaje HTTP contiene toda la información necesaria para comprender la petición. Ni cliente ni servidor necesitan recordar ningún estado.
• Operaciones bien definidasHTTP en sí define un conjunto de operaciones: POST, GET, PUT y DELETE.
• Sintaxis universalCada recurso es direccionable únicamente a través de su URI.
• Soporte multiformatoHTML, XML, etc.
¿Cuándo usamos REST?
Servicio Web sin estado Productor y consumidor
conocen el contexto y contenido
Ancho de banda importante y necesita ser limitado
Distribución de Servicios Web o agregación de sitios Web existentes
Requerimientos complejos no funcionales:
TransaccionesInformación contextualEstado
Contrato formal con funcionalidad de la interfaz (WSDL)Procesado asíncrono
REST + Spring
REST en Spring MVC Configuración
web.xml<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters --><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value></context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters --><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
<!-- Processes application requests --><servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet>
<servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping>
</web-app>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value></context-param>
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet>
<servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping>
REST en Spring MVC Configuración
*-context.xml<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model --><annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --><resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean>
<context:component-scan base-package="com.paradigma.example" />
</beans:beans>
<annotation-driven /> <context:component-scan base-package="com.paradigma.example" /><beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean>
REST en Spring MVC Configuración
pom.xml<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.paradigma</groupId><artifactId>example</artifactId><name>example</name><packaging>war</packaging><version>1.0.0-BUILD-SNAPSHOT</version><properties><java-version>1.6</java-version><org.springframework-version>3.1.0.RELEASE</org.springframework-version><org.aspectj-version>1.6.9</org.aspectj-version><org.slf4j-version>1.5.10</org.slf4j-version></properties><dependencies><!-- Spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${org.springframework-version}</version><exclusions><!-- Exclude Commons Logging in favor of SLF4j --><exclusion><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${org.springframework-version}</version></dependency>…..<plugins>plugins></build></project>
<properties><java-version>1.6</java-version><org.springframework-version>3.1.0.RELEASE</org.springframework-version><org.aspectj-version>1.6.9</org.aspectj-version><org.slf4j-version>1.5.10</org.slf4j-version>
</properties>
<dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.6.4</version>
</dependency>
REST en Spring MVC 3.0Controladores
• @PathVariable• Negociación del contenido• @RequestBody/@ResponseBody/@ResponseStatus• Validación en la declaración: @Valid
@Controller@RequestMapping("/person")public class PersonController {
@RequestMapping(value = “/", method = RequestMethod.GET)
public Person person(@RequestParam String id, Model model) {…} }
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@PathVariable
@RequestMapping(value = "/{id}", method = RequestMethod.GET ,produces = "application/xml")
@ResponseBody
Hello REST!
Servicio REST con Spring MVCCaso práctico
Diseño de la interfaz
• Identificar entidades conceptuales
• Crear una URI para cada recurso (nombres, no verbos)
https://www.myrest.com/tvshowrest/provider/tvshow/{id}
• Definir que métodos son soportados por cada URIGET, PUT y DELETE
• Formato de cada recursoXML
• id•name• genre• year• rates
TVShow
¿Preguntas?