SlideShare a Scribd company logo
Spring 3 MVC Rest  (3.0.5 기준)김용환Knight76 at gmail.comKnight76.tistory.com맛보기
특징REST를 쓰기 위해서 Spring MVC 모델을 그대로 차용, Annotation 이용(Controller)JSR 311을 따르지는 않지만, 대부분의 기능 구현하나의 리소스는 여러 개의 Represenation을 가질 수있도록함 (JSON/XML/ATOM/RSS)브라우저에서 지원하지 않는 PUT & POST 요청을 처리할 수 있음Custom parser 이용 가능UTIL(converter..) 클래스 지원=> REST 관련 Conception만 조금 공부하면 되고, 나머지는 기존 MVC만 알면 되기 까닭에재사용성이 큼
Spring 3 Rest 지원#1Annotation 지원 @Controller : MVC@RequestMapping : HTTP 메소드, URI, 헤더 처리@RequestMapping(method=RequestMethod.GET, value="/members", @PathVariable: 메소드 안에서 파라미터와매핑하기 위해서 사용public ModelAndViewgetEmployee(@PathVariable String id) { … } @RequestParam : URL 매개변수 이용@RequestHeader@RequestBody@HttpEntity<T>@ResponseEntity<T> : 정의한대로 response 리턴public @ResponseBody Employee getEmployeeBy(@RequestParam("name") String name, @RequestHeader("Accept") String accept, @RequestBody String body) {…} public ResponseEntity<String> method(HttpEntity<String> entity) {…}
Spring 3 Rest 지원 #1Annotation 지원@ResponseStatus@ExceptionHandler

Recommended for you

Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application

Slides from my tutorial on creating a websocket chat application using Java EE 7, GlassFish4, Maven, Bootstrap and jQuery.

chatbootstrapjavaee
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)

In this talk we will present a middleware async architecture based on Expressive and Swoole to speed up web API development and runtime in PHP. Using this approach, you will be able to achieve great performance improvement, up to 4x faster than nginx or Apache (benchmark).

expressiveswoolephpweb apis
Session 40 : SAGA Overview and Introduction
Session 40 : SAGA Overview and Introduction Session 40 : SAGA Overview and Introduction
Session 40 : SAGA Overview and Introduction

This document provides an introductory lecture on SAGA (Simple API for Grid Applications) and distributed applications. It discusses SAGA as an emerging standard and how SAGA can be used to develop distributed applications by providing a simple, uniform interface that hides complexity. The document outlines challenges in distributed applications and provides a taxonomy of distributed applications based on computational models, usage modes, and level of coordination between components.

jhashantenuapi
Spring 3 Rest 지원 #2ContentNegotiatingViewResolver요청 데이터 포맷에 맞춰 다양한 MIME(미디어 타입) 이나 content type으로 전달 가능ATOM, RSS, XML, JSON, OXM예)http://localhost:8080/fruit/banana.xmlhttp://localhost:8080/fruit/banana.rsshttp://localhost:8080/fruit/banana.htmlAccept : application/xmlAccept : application/jsonAccept : application/html
좋은자료http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.htmlhttp://dev.anyframejava.org/docs/anyframe/plugin/restweb/1.0.1/reference/html/index.htmlhttp://www.mkyong.com/spring-mvc/spring-3-mvc-contentnegotiatingviewresolver-example/http://www.ibm.com/developerworks/web/library/wa-spring3webserv/index.htmlhttp://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
개념 살펴보기
@Controller@Controller@RequestMapping("/restful")public class RestfulController {@RequestMapping(value = "/message/{name}", method = RequestMethod.GET)	public String getMessage(@PathVariable String name, ModelMap model) {model.addAttribute("message", name);		return "list";	}…}

Recommended for you

Unify Earth Observation products access with OpenSearch
Unify Earth Observation products access with OpenSearchUnify Earth Observation products access with OpenSearch
Unify Earth Observation products access with OpenSearch

CEOS WGISS 35 - Sao Jose dos Campos, Brazil - 2013.05.08 OpenSearch applied to Earth Observations products

opensearchrdfeo
Your rest api using laravel
Your rest api using laravelYour rest api using laravel
Your rest api using laravel

This document discusses building REST APIs using Laravel. It covers topics like HTTP methods, status codes, authentication, caching, pagination, versioning and more. Meticulous explanations are provided for concepts like authenticating applications/clients using OAuth 2 and authenticating users with basic authentication and access tokens. Examples are given for CRUD operations on a users resource, showing the requests and responses for creating, retrieving, updating and deleting users.

menggunakanrestapi
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8

Web servers and browsers have security vulnerabilities that can allow attackers to compromise systems. A simple Java-based web server has vulnerabilities like denial of service attacks if it does not properly handle requests. Attackers can also exploit vulnerabilities in web applications, servers, or browsers like directory traversal, script permissions, and default files and samples to steal or modify data or deny access. It is important to secure web servers and applications by applying patches, limiting privileges and permissions, removing unnecessary files and services, and using security products.

Request Parameter TypeStrong@Controller@RequestMapping("/restful")public class RestfulController {	@RequestMapping(value = "/message/{name}", method = RequestMethod.GET)	public String getMessage(@PathVariableString name, ModelMap model) {model.addAttribute("message", name);		return "list";	}…}
@PathVariable@Controller@RequestMapping("/restful")public class RestfulController {	@RequestMapping(value = "/message/{name}", method = RequestMethod.GET)	public String getMessage(@PathVariable String name, ModelMap model) {model.addAttribute("message", name);		return "list";	}…}
@ResponseBody@Controller@RequestMapping("/restful")public class RestfulController {@RequestMapping(value = "/messagebody/{message}", method = RequestMethod.GET)@ResponseBodypublic Body getMessageBody(@PathVariable String message, ModelMap model) {Body body = new Body();body.setMessage(message);return body;}…}@XmlRootElement(name = "body")public class Body {@XmlElementprivate String msg;public String getMessage() {   return msg;}public void setMessage(String message) {    this.msg = message;}}
@ResponseStatus@RequestMapping(value = "/exception", method = RequestMethod.GET)public String throwException() {    throw new ResourceNotFoundException();}@ExceptionHandler(ResourceNotFoundException.class)@ResponseStatus(value = HttpStatus.BAD_GATEWAY) public void handleNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) {System.out.println("handleNotFoundException:" + ex);}…..class ResourceNotFoundException extends RuntimeException { } $ curl -i  localhost:8080/restful/exceptionHTTP/1.1 502 Bad GatewayContent-Length: 0Server: Jetty(6.1.26)결과

Recommended for you

BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYBUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY

How to get up and running in minutes with the lean, scalable, and easy to maintain Python web framework, Flask. Attendees will get to see how Flask acts as the sturdy glue between your database framework, front-end templates and operating system. Keep an eye out for tips/tricks using SQLite, Jinja2, and Werkzeug. Neil is a software developer with a background in 3D graphics programming and management information systems. Presently he's working with Image Engine on feature-film visual effects projects like Teenage Mutant Ninja Turtles, Elysium, Fast & Furious. He's also a co-founder of ComboMash Entertainment, an independent game studio based in Vancouver.

flaskweb frameworkspython framework
Pulsar Architectural Patterns for CI/CD Automation and Self-Service
Pulsar Architectural Patterns for CI/CD Automation and Self-ServicePulsar Architectural Patterns for CI/CD Automation and Self-Service
Pulsar Architectural Patterns for CI/CD Automation and Self-Service

We examine real-world architectural patterns involving Apache Pulsar to automate the creation of function and pub/sub flows for improved operational scalability and ease of management. We’ll cover CI/CD automation patterns and reveal our innovative approach of leveraging streaming data to create a self-service platform that automates the provisioning of new users. We will also demonstrate the innovative approach of creating function flows through patterns and configuration, enabling non-developer users to create entire function flows simply by changing configurations. These patterns enable us to drive the automation of managing Pulsar to a whole new level. We also cover CI/CD for on-prem, GCP, and AWS users.

apacheapache pulsarkafka
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python

The document discusses developing REST APIs with Python and Django Rest Framework (DRF). It explains the basics of REST, why it is used, and how to build a REST API with DRF including serializers, views, URLs, permissions, versioning, documentation, and testing. DRF allows building web APIs with Django that are highly configurable and have little boilerplate code. It also supports non-ORM data sources.

djangoapipython
Rest 방식과 기존 파라미터요청 방식 을 같이 사용가능??@RequestMapping(value = "/test/{name}/id/{id}", method = RequestMethod.GET)public String getString(@PathVariable String name, @PathVariableint id,                                 String email, ModelMap model) {model.addAttribute("message", name);model.addAttribute("id", id);model.addAttribute("email", email);    return "test";}가능// test.jsp<html><head></head><body><h1>Test</h1><h3>message : ${message}</h3><h3>email : ${email}</h3></body></html>$ curl http://localhost:8080/restful/test/jaja/id/11?email=aaa@google.com<html><head></head><body>        <h1>Test</h1>        <h3>message : jaja</h3>        <h3>email : aaa@google.com</h3></body></html>결과
JSON Payload 요청 #1@Controller@RequestMapping("/comm")@ResponseStatus(value = HttpStatus.ACCEPTED)public class JsonRequestController {    @RequestMapping(method = RequestMethod.GET)     @ResponseStatus(value=HttpStatus.FOUND)    public void sendFruitMessage(@RequestBody Message name) {System.out.println("name : " + name.getName());        return ;    }}Spring MVC가 알아서 deserialization을 해줌@XmlRootElement(name = "message")public class Message {@XmlElementprivate String name;public String getName() {return name;}      public void setName(String name) {	this.name = name;     }}
JSON Payload 요청 #2결과 : xml <클라이언트>$ curl -i -H "Content-Type: application/xml" -X get -d '<message><name>Kim Yong Hwan</name></message>' localhost:8080/commHTTP/1.1 302 FoundContent-Length: 0Server: Jetty(6.1.26)<서버>name : Kim Yong Hwan결과 : json<클라이언트>$ curl  -i -H "Content-Type: application/json" -X get -d '{"name":"Kim Yong Hwan"}' localhost:8080/commHTTP/1.1 302 FoundContent-Length: 0Server: Jetty(6.1.26)<서버>name : Kim Yong Hwan
DEMO

Recommended for you

Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions

Slides contain RESTful solutions based on Python frameworks like Flask and Django. The presentation introduce in REST concept, presents benchmarks and research for best solutions, analyzes performance problems and shows how to simple get better results. Finally presents soruce code in Flask and Django how to make your own RESTful API in 15 minutes.

flaskrestrestful
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices

This document introduces Flask, a Python microframework for building web applications and APIs. It shows how to create a basic "Hello World" Flask app in 3 steps: creating the Flask object, defining a route, and returning a JSON response. It then demonstrates various response types like simple text, generators, and files. It covers routing concepts like dynamic routes, default values, and REST verbs. More advanced topics discussed include static file serving, database connections, exception handling, and using blueprints to organize routes.

pythonrestfulflask
On UnQLite
On UnQLiteOn UnQLite
On UnQLite

UnQLite is an embedded key-value and document-oriented database with a simple API similar to SQLite. It uses a BSD license and supports cross-platform usage. Benchmarks show it has comparable or better performance than SQLite, Berkeley DB and other databases for common operations like storing, fetching, and iterating over large amounts of data. The developer is working on adding new storage engines to UnQLite.

perl unqlite
WEB.XML<web-app id="WebApp_ID" version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><display-name>Spring Web MVC Rest Demo Application</display-name><servlet>    <servlet-name>mvc-dispatcher</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>mvc-dispatcher</servlet-name>    <url-pattern>/</url-pattern></servlet-mapping><context-param>    <param-name>contextConfigLocation</param-name>    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value></context-param><listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>
mvc-dispatcher-servlet.xml<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="        http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:component-scan base-package="com.google.controller" /><mvc:annotation-driven /><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="prefix" value="/WEB-INF/pages/" />    <property name="suffix" value=".jsp" /></bean></beans>
RestfulController.java@Controller@RequestMapping("/restful")public class RestfulController {@RequestMapping(value = "/message/{name}", method = RequestMethod.GET)	public String getMessage(@PathVariable String name, ModelMap model) {model.addAttribute("message", name);		return "list";	}@RequestMapping(value = "/command/{id}/content/{content}", method = RequestMethod.GET)	public String getCommand(@PathVariable("id") String id, @PathVariable("content") long content, ModelMap model) {model.addAttribute("id", id);model.addAttribute("content", content);		return "command";	}@RequestMapping(value = "/link/{id}", method = RequestMethod.DELETE)	public String deleteLink(@PathVariable("id") String id, ModelMap model) {model.addAttribute("id", id);		return "delete";	}}
JSP 소스// WEB-INF/pages/list.jsp<html><body><h1>Spring MVC Restful Test</h1><h3>message : ${message}</h3></body></html>// WEB-INF/pages/command.jsp<html><body><h1>Spring MVC Restful Test</h1>    <h3>command id : ${id}</h3><h3>content : ${content}</h3></body></html>// WEB-INF/pages/delete.jsp<html><body><h1>Spring MVC Restful Test</h1><h3>deleted id : ${id}</h3></body></html>

Recommended for you

An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr

The document discusses the open source search platform Solr, describing how it provides a RESTful web interface and Java client for full text search capabilities. It covers installing and configuring Solr, adding and querying data via its HTTP API, and using the SolrJ Java client library. The presentation also highlights key Solr features like faceting, filtering, and scaling for performance.

searchjavalucene
Rest in flask
Rest in flaskRest in flask
Rest in flask

The document discusses building REST APIs in Flask. It introduces REST concepts and how Flask supports REST. Validation of resources can be done with Trafaret. The document demonstrates creating API resources with Flask extensions that support validation, authentication decorators, and modeling SQL Alchemy classes. Future work includes adding filtering, caching, throttling and customizing fields for modeled resources.

flaskrestpython
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace

DTrace is a comprehensive dynamic tracing framework created by Sun Microsystems for troubleshooting kernel and application problems on production systems in real time. It provides probes in the operating system and applications to monitor events, collects and aggregates data, and provides tools to analyze the data. DTrace can be used on Unix-like systems like Solaris, Linux, macOS, and in Node.js applications through a DTrace provider. It allows gathering insights about the system and application behavior without restarting or slowing the system.

node.jsdtrace
결과 (웹 브라우저)http://localhost:8080/restful/message/resethttp://localhost:8080/restful/command/aa/content/111
결과 (리눅스/Cygwin)curl -X DELETE http://localhost:8080/restful/link/1 curl -X DELETE http://localhost:8080/restful/message/3
Content Negotiation
Content NegotiationHTTP 1.1 스펙에서 정의의미media type, 언어, 문자집합, 인코딩 등에 대해 브라우저가 제공한 선호도에 따라 자원의 가장 적합한 표현을 선택. 불완전한 협상 정보를 보내는 브라우저의 요청을 지능적으로 처리하는 기능일반적으로 다른 프로토콜을 쓰려면, request의 “type” 파라미터를 확인하고, 이에 맞는 marshalling정보를 전달해야 한다.트위터API가 이렇게 사용되고 있음Spring MVC에서는 한번에 해결해주는 클래스 사용 ContentNegotiatingViewResolver

Recommended for you

Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long

This document provides an overview of Spring's support for building multi-client web applications. It discusses Spring's servlet support including the Servlet 3.0 initializer classes. It also covers Spring MVC, building mobile-friendly applications, native Android development with Spring, REST support, and securing applications with Spring Security. The document contains examples of core Spring features like controllers and uses diagrams to illustrate classic Spring MVC architecture. It aims to demonstrate these techniques through examples and code snippets.

html5oauthjosh long
Information security programming in ruby
Information security programming in rubyInformation security programming in ruby
Information security programming in ruby

Original: https://docs.google.com/presentation/d/1ZzyRp_xzbcHP5LJGHB-iDkj3bxDj0h1p97dEkxmZJUE/edit?usp=sharing

securityrubyjruby
ITU Letter to the President of Indonesia (IM2 Case)
ITU Letter to the President of Indonesia (IM2 Case)ITU Letter to the President of Indonesia (IM2 Case)
ITU Letter to the President of Indonesia (IM2 Case)

ITU Letter to the President of Indonesia (IM2 Case)

im2internet indonesiabroadband
DEMO
FruitController@Controller@RequestMapping("/fruit")public class FruitController{    @RequestMapping(value="{fruitName}", method = RequestMethod.GET)    public String getFruit(@PathVariable String fruitName, ModelMap model) {    Fruit fruit = new Fruit(fruitName, 1000);model.addAttribute("model", fruit);    return "listfruit";    }}
Fruit@XmlRootElement(name = "fruit")public class Fruit {String name;intquality;public Fruit() {}public Fruit(String name, int quality) {    this.name = name;this.quality = quality;}@XmlElementpublic void setName(String name) {this.name = name;}@XmlElementpublic void setQuality(int quality) {this.quality = quality;}}
mvc-dispatcher-servlet.xml<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  <property name="order" value="1" />  <property name="mediaTypes"><map>   <entry key="json" value="application/json" />   <entry key="xml" value="application/xml" />   <entry key="rss" value="application/rss+xml" /></map>  </property>  <property name="defaultViews"><list>    <beanclass="org.springframework.web.servlet.view.json.MappingJacksonJsonView">  </bean>    <bean class="com.google.rss.RssFeedView" />    <bean class="org.springframework.web.servlet.view.xml.MarshallingView"><constructor-arg><bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">   <property name="classesToBeBound"><list>   <value>com.google.bean.Fruit</value></list>   </property></bean></constructor-arg>  </bean> </list>  </property>  <property name="ignoreAcceptHeader" value="true" /></bean><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="order" value="2" /><property name="prefix" value="/WEB-INF/pages/" /><property name="suffix" value=".jsp" /></bean>

Recommended for you

Poly Clip Zertificate
Poly Clip ZertificatePoly Clip Zertificate
Poly Clip Zertificate
Ejecucion presupuesto 2012_2014
Ejecucion presupuesto 2012_2014Ejecucion presupuesto 2012_2014
Ejecucion presupuesto 2012_2014

El documento resume la ejecución presupuestal de la Universidad Nacional Federico Villarreal (UNFV) durante los años 2012-2014. En el año 2012, la UNFV alcanzó una ejecución presupuestal consolidada de 93.3%, superando a otras universidades públicas, al sector educación y al gobierno nacional. En 2013 la ejecución fue de 85.2% y en 2014 fue de 89.4%. El documento analiza los detalles de la ejecución por fuente de financiamiento y genéricas de gasto para cada año.

Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, SaylaJanhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla

Janhit, the official annual humanitarian publication by Raj Saubhag Ashram, Sayla, celebrates the vast spectrum of humanitarian activities. Bhaishree's compassion, humility and foresight guide this work. His virtues display a humanity which facilitates a great spiritual and charitable impact. The magazine is written in good English and will enable us to keep well informed of these activities. It is colourful and very well illustrated. There are a number of case studies and each field of activity is given a different code.

결과$ curl -H 'Accept: application/xml' localhost:8080/fruit/banana.xml<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fruit><name>banana</name><quality>1000</quality></fruit>$ curl -H 'Accept: application/rss'localhost:8080/fruit/banana.rss<?xml version="1.0" encoding="UTF-8"?><rssxmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">  <channel>    <title>Sample Title</title>    <link>http://google.com</link>    <description>Sample Description</description>    <item>      <link>http://www.google.com</link>      <content:encoded>banana1000</content:encoded>      <author>Test</author>    </item>  </channel></rss>$ curl -H 'Accept: application/json' localhost:8080/fruit/banana.json{"model":{"quality":1000,"name":"banana"}}
Demo에서 @XmlElement사용시 유의할 점Set메소드를 사용하려면, 다음과 같이 한다.  클래스의 멤버 필드에서 @XmlElement를 정의할 때는 set 메소드를 사용하지 않는다. @XmlRootElement(name = "fruit")public class Fruit {    private String name;    private int quality;@XmlElement        public void setBody(Body body) {this.body= body;    }    public String getName() {        return name;    }@XmlElement    public void setQuality(int quality) {this.quality= quality;    }    public intgetQuality() {       return quality;    }…}@XmlRootElement(name = "fruit")public class Fruit {@XmlElement    private String name;@XmlElement    private int quality;    public String getName() {        return name;    }    public intgetQuality() {       return quality;    }…}JAXB에서 property를 읽을 때, 잘 사용해야 하는 구조
Demo에서 @XmlElement사용시유의할 점Body 클래스앞에@XmlRootElement선언이 되어 있으면, Fruit 클래스 에서 @XmlElement를 사용하지 않아도 된다.@XmlRootElement(name = "body")public class Body {    @XmlElement    private String msg;     // set/get accessory ….}@XmlRootElement(name = "fruit")public class Fruit {@XmlElement    private String name;@XmlElement    private int quality;    private Body body;    public String getName() {        return name;    }    public intgetQuality() {       return quality;    }…}
웹 브라우져에서의PUT/DELETE의 제약

Recommended for you

Aplicando lo aprendido con las tic
Aplicando lo aprendido con las ticAplicando lo aprendido con las tic
Aplicando lo aprendido con las tic

aplicando los conocimientos adquiridos en el uso de las Tic

Cl130
Cl130Cl130
Cl130

1. O documento fornece instruções de segurança e uso para um produto de áudio. 2. Inclui instruções sobre como preparar o produto para uso, configurá-lo, alimentá-lo e solucionar problemas. 3. Também descreve funções como reprodução de CDs, rádio FM/AM, USB e gravação de áudio.

retrotourne disquejukebox
PAFonteyne_ExtendedCV_2015
PAFonteyne_ExtendedCV_2015PAFonteyne_ExtendedCV_2015
PAFonteyne_ExtendedCV_2015

Pierre-Alain Myron Paul Fonteyne has over 25 years of experience in microbiology, molecular biology, biosafety, and project management. He has worked at several research institutions in Belgium, including the Université catholique de Louvain and the Scientific Institute of Public Health. He has led numerous projects funded by the European Commission involving biological threats and security research. He has also founded a spin-off company focusing on microbial pollution monitoring. Throughout his career, he has published over 30 papers, supervised PhD students from various countries, and delivered training internationally. Currently he works as a biosecurity researcher focusing on transferring knowledge in biological threats to European security research topics.

웹 브라우져 제약 #1GET/POST만 쓸 수 있는 웹 브라우져가 있을 수 있다. PUT과 DELETE 을 쓰기 위해서는 trick을 써야 한다.HiddenHttpMethodFilter이용Web.xml  <filter>        <filter-name>httpMethodFilter</filter-name>        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>    </filter>        <filter-mapping>        <filter-name>httpMethodFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>
웹 브라우져 제약 #2// spring mvc form tag<form:form method="delete"> <p class="submit"><input type="submit" value="Delete Pet"/></p> </form:form>@RequestMapping(method = RequestMethod.DELETE)public String deletePet(@PathVariableintownerId, @PathVariableintpetId) {this.clinic.deletePet(petId);    return "redirect:/owners/" + ownerId;}아마도 예전처럼 내부적으로 name=“_method” value=“Delete” 하는 형태로 전달하고, Spring 서버는 이 정보를 바탕으로 구현 했을 것으로 예상<form action="POST">  <input type="hidden" id="_method" value="PUT"></form>
PUT/DELETE in HTMLHTML version 4 과 XHTML 1에서는 HTML  form안의 HTTP 요청은 GET과 POST 방식만 허용. 그동안put/delete 메소드를 사용하려면, XMLHttpRequest를 이용하였음HTTP상에서는 ok!HTML5에서 put/delete는 사용하지 못한다고 나와 있음http://www.w3.org/TR/html5-diff/Using PUT and DELETE as HTTP methods for the form element is no longer supported.참고
클라이언트 API : RestTemplate

Recommended for you

Elastische Skalierbarkeit für Web-Anwendungen
Elastische Skalierbarkeit für Web-AnwendungenElastische Skalierbarkeit für Web-Anwendungen
Elastische Skalierbarkeit für Web-Anwendungen

Vortrag auf der Informatik 2012 zum Workshop "Architekturen für Services & Cloud Computing" des SOA Innovation Lab E.V.

playakkaweb 2.0
Info mipa p85 lang
Info mipa p85 langInfo mipa p85 lang
Info mipa p85 lang

Mipa P 85 is a bright white, easy to sand two-component finishing putty based on polyester resin. It is applied in thin layers as a top coat over polyester fillers to close pinholes, irregularities, and small damages on car bodies. It has high filling power, elasticity, and adhesion to various substrates. It dries within 15 minutes and can then be sanded or overcoated with various paint systems. Proper ventilation is required when using and the hardener ratio must be followed to avoid staining.

Zanox se instala en España. Sep2003. Revista Estrategias.
Zanox se instala en España. Sep2003. Revista Estrategias. Zanox se instala en España. Sep2003. Revista Estrategias.
Zanox se instala en España. Sep2003. Revista Estrategias.

Zanox, una compañía alemana de marketing digital, abre operaciones en España para aprovechar el crecimiento de las empresas españolas que usan Internet para promocionar ventas. Zanox ofrece soluciones de marketing digital a bajo costo como afiliación, email marketing y publicidad en buscadores. El director general de Zanox Hispania dice que Zanox satisface la demanda creciente de soluciones profesionales de marketing promocional en Internet.

sergio garasazanox españasergio garasa mayayo
클라이언트 APIApache Commons의 HttpClient대신 쉽게 사용할 수 있는 RestTemplate구성<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"><property name="messageConverters">	<list>	<ref bean="marshallingConverter" />	<ref bean="atomConverter"  />	<ref bean="jsonConverter" />	</list></property></bean>
클라이언트 APIXML 요청HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_XML);HttpEntity<String> entity = new HttpEntity<String>(headers);ResponseEntity<EmployeeList> response = restTemplate.exchange("http://localhost:8080/rest/service/emps", HttpMethod.GET, entity, EmployeeList.class);EmployeeListingemployees = response.getBody();// handle the employees
클라이언트 API새직원포스팅/ 삭제Employee newEmp = new Employee(11, “tguest", “tguest@google.com");HttpEntity<Employee> entity = new HttpEntity<Employee>(newEmp);restTemplate.put(	"http://localhost:8080/rest/service/emp/{id}", entity, "99");restTemplate.delete(	"http://localhost:8080/rest/service/emp/{id}", "99");
RestTemplate클래스클라이언트에서 사용할 수 있는 Rest API

Recommended for you

Consigli & Ricette per piccoli gourmet
Consigli & Ricette per piccoli gourmetConsigli & Ricette per piccoli gourmet
Consigli & Ricette per piccoli gourmet

Partial version of the book "Tips & Recipes for small gourmet" by the chef Heinz Beck, the FIMP President Dr. Joseph Mele, and the peditrician Dr. Adima Lamborghini. Made with help of FIMP, Italian Federation of Doctors Pediatricians. DOWNLOAD FOR FREE http://www.equivalente.it by simply registering! Versione parziale del volume "Consigli & Ricette per piccoli gourmet" a cura dello chef Heinz Beck, del Dottor Giuseppe Mele, presidente FIMP, e della Dottoressa Adima Lamborghini, medico pediatra. Realizzato con il contributo di FIMP, Federazione Italiana Medici Pediatri. SCARICALO GRATIS da http://www.equivalente.it semplicemente registrandoti!

nutritionmedicinehealth
Portafolio de Cultura Neuroactiva
Portafolio de Cultura NeuroactivaPortafolio de Cultura Neuroactiva
Portafolio de Cultura Neuroactiva

Este documento describe los servicios ofrecidos por Cultura Neuroactiva, una organización que trabaja en el campo de la salud mental y el bienestar. Ofrece cuatro líneas principales de servicios: terapéuticos, educativos, de salud organizacional y de salud pública. También describe su centro de investigación, fundación y portal web. Los servicios terapéuticos incluyen terapia y neuroestimulación, y los servicios educativos incluyen varios cursos y seminarios relacionados con la salud mental.

brochure ck line
brochure ck linebrochure ck line
brochure ck line

The document provides information about CK Line's vessel fleet and global network. It lists 18 vessels that CK Line operates on various trade routes between Korea, Japan, China, Southeast Asia, and other regions. It also outlines CK Line's offices in key ports around Asia and describes several container liner services covering routes like Hong Kong - Vietnam - Thailand and Incheon - Busan - Shanghai - Manila.

RestTemplate클래스
RestTemplate예제Map<String, String> vars = new HashMap<String, String>();vars.put("id", "111");vars.put("content", "222");RestTemplaterestTemplate = new RestTemplate();String result = restTemplate.getForObject("http://localhost:8080/restful/command/{id}/content/{content}", String.class, vars);System.out.println("result : " + result);result : <html><body><h1>Spring MVC Restful Test</h1>    <h3>command id : 111</h3><h3>content : 222</h3></body></html>결과
ExampleCodeKnight76.tistory.com에서 ‘spring mvc restful’ 검색
End of Document

Recommended for you

Omam Consultants Presentation
Omam Consultants   PresentationOmam Consultants   Presentation
Omam Consultants Presentation

Omam Consultants Private Limited is a leading HR consulting and staffing firm in India with over 100 professionals across multiple offices. They have over 25 years of experience serving over 200 clients in 50 different industries. Their services include recruitment, HR consulting, compensation solutions, and other HR services. They aim to provide innovative and cost-effective HR solutions to achieve client satisfaction.

Manejo del embarazo no deseado (1)
Manejo del embarazo no deseado (1)Manejo del embarazo no deseado (1)
Manejo del embarazo no deseado (1)

1) El documento resume una mesa redonda sobre el embarazo no deseado realizada en el Hospital San Bartolomé en Lima, Perú en 2012. 2) Los expositores discutieron temas como la etiología, consecuencias y manejo del embarazo no deseado. 3) El Dr. Percy Pacora presentó sobre el manejo del embarazo no deseado, enfatizando la importancia de dar fe, mostrar al niño, dar esperanza e involucrar a la familia y la sociedad.

Musica
MusicaMusica
Musica

La música rock se centra principalmente en la guitarra eléctrica, el bajo y la batería. Generalmente tiene un ritmo de 4/4 y una estructura de verso-coro. Aunque originalmente se enfocaba en el amor, también explora una variedad de temas sociales y políticos. El rock ha servido como vehículo para importantes movimientos culturales y sociales como la contracultura hippie de los años 60. También se asocia con el activismo político y cambios en actitudes hacia el racismo, el sexo y las drogas.

More Related Content

What's hot

httpie
httpiehttpie
Advancedservletsjsp
AdvancedservletsjspAdvancedservletsjsp
Advancedservletsjsp
Pradeep Raikwar
 
WSO2Con USA 2015: Securing your APIs: Patterns and More
WSO2Con USA 2015: Securing your APIs: Patterns and MoreWSO2Con USA 2015: Securing your APIs: Patterns and More
WSO2Con USA 2015: Securing your APIs: Patterns and More
WSO2
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
Micha Kops
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Zend by Rogue Wave Software
 
Session 40 : SAGA Overview and Introduction
Session 40 : SAGA Overview and Introduction Session 40 : SAGA Overview and Introduction
Session 40 : SAGA Overview and Introduction
ISSGC Summer School
 
Unify Earth Observation products access with OpenSearch
Unify Earth Observation products access with OpenSearchUnify Earth Observation products access with OpenSearch
Unify Earth Observation products access with OpenSearch
Gasperi Jerome
 
Your rest api using laravel
Your rest api using laravelYour rest api using laravel
Your rest api using laravel
Sulaeman .
 
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8
Ali Habeeb
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYBUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
CodeCore
 
Pulsar Architectural Patterns for CI/CD Automation and Self-Service
Pulsar Architectural Patterns for CI/CD Automation and Self-ServicePulsar Architectural Patterns for CI/CD Automation and Self-Service
Pulsar Architectural Patterns for CI/CD Automation and Self-Service
Devin Bost
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
Santosh Ghimire
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices
Marcos Lin
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLite
charsbar
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr
tomhill
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
Yehor Nazarkin
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
JeongHun Byeon
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
jaxconf
 
Information security programming in ruby
Information security programming in rubyInformation security programming in ruby
Information security programming in ruby
Hiroshi Nakamura
 

What's hot (20)

httpie
httpiehttpie
httpie
 
Advancedservletsjsp
AdvancedservletsjspAdvancedservletsjsp
Advancedservletsjsp
 
WSO2Con USA 2015: Securing your APIs: Patterns and More
WSO2Con USA 2015: Securing your APIs: Patterns and MoreWSO2Con USA 2015: Securing your APIs: Patterns and More
WSO2Con USA 2015: Securing your APIs: Patterns and More
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
 
Session 40 : SAGA Overview and Introduction
Session 40 : SAGA Overview and Introduction Session 40 : SAGA Overview and Introduction
Session 40 : SAGA Overview and Introduction
 
Unify Earth Observation products access with OpenSearch
Unify Earth Observation products access with OpenSearchUnify Earth Observation products access with OpenSearch
Unify Earth Observation products access with OpenSearch
 
Your rest api using laravel
Your rest api using laravelYour rest api using laravel
Your rest api using laravel
 
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYBUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
 
Pulsar Architectural Patterns for CI/CD Automation and Self-Service
Pulsar Architectural Patterns for CI/CD Automation and Self-ServicePulsar Architectural Patterns for CI/CD Automation and Self-Service
Pulsar Architectural Patterns for CI/CD Automation and Self-Service
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLite
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
Information security programming in ruby
Information security programming in rubyInformation security programming in ruby
Information security programming in ruby
 

Viewers also liked

ITU Letter to the President of Indonesia (IM2 Case)
ITU Letter to the President of Indonesia (IM2 Case)ITU Letter to the President of Indonesia (IM2 Case)
ITU Letter to the President of Indonesia (IM2 Case)
ICT Watch
 
Poly Clip Zertificate
Poly Clip ZertificatePoly Clip Zertificate
Poly Clip Zertificate
Ramon Ortega
 
Ejecucion presupuesto 2012_2014
Ejecucion presupuesto 2012_2014Ejecucion presupuesto 2012_2014
Ejecucion presupuesto 2012_2014
Vrac Unfv
 
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, SaylaJanhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Raj Saubhag
 
Aplicando lo aprendido con las tic
Aplicando lo aprendido con las ticAplicando lo aprendido con las tic
Aplicando lo aprendido con las tic
luz dary delgado bedoya
 
Cl130
Cl130Cl130
PAFonteyne_ExtendedCV_2015
PAFonteyne_ExtendedCV_2015PAFonteyne_ExtendedCV_2015
PAFonteyne_ExtendedCV_2015
Pierre-Alain Fonteyne
 
Elastische Skalierbarkeit für Web-Anwendungen
Elastische Skalierbarkeit für Web-AnwendungenElastische Skalierbarkeit für Web-Anwendungen
Elastische Skalierbarkeit für Web-Anwendungen
Axel Irriger
 
Info mipa p85 lang
Info mipa p85 langInfo mipa p85 lang
Info mipa p85 lang
car coatings system (thailand)
 
Zanox se instala en España. Sep2003. Revista Estrategias.
Zanox se instala en España. Sep2003. Revista Estrategias. Zanox se instala en España. Sep2003. Revista Estrategias.
Zanox se instala en España. Sep2003. Revista Estrategias.
Retelur Marketing
 
Consigli & Ricette per piccoli gourmet
Consigli & Ricette per piccoli gourmetConsigli & Ricette per piccoli gourmet
Consigli & Ricette per piccoli gourmet
Piero Conte
 
Portafolio de Cultura Neuroactiva
Portafolio de Cultura NeuroactivaPortafolio de Cultura Neuroactiva
Portafolio de Cultura Neuroactiva
Cultura Neuroactiva
 
brochure ck line
brochure ck linebrochure ck line
brochure ck line
Dinda Artya
 
Omam Consultants Presentation
Omam Consultants   PresentationOmam Consultants   Presentation
Omam Consultants Presentation
aopu64
 
Manejo del embarazo no deseado (1)
Manejo del embarazo no deseado (1)Manejo del embarazo no deseado (1)
Manejo del embarazo no deseado (1)
Percy Pacora Portella
 
Musica
MusicaMusica
Musica
kamii12
 
Bits arte y formas geométricas
Bits arte y formas geométricasBits arte y formas geométricas
Bits arte y formas geométricas
Miriam Sedes López
 
GKA deel 1 college 9
GKA deel 1 college 9GKA deel 1 college 9
GKA deel 1 college 9
Biology, Utrecht University
 
Calendario de Actividades en Acapulco
Calendario de Actividades en AcapulcoCalendario de Actividades en Acapulco
Calendario de Actividades en Acapulco
José Salgado Vázquez
 
Factor 10. Recursos Físicos y Financieros
Factor 10. Recursos Físicos y FinancierosFactor 10. Recursos Físicos y Financieros
Factor 10. Recursos Físicos y Financieros
sisauq
 

Viewers also liked (20)

ITU Letter to the President of Indonesia (IM2 Case)
ITU Letter to the President of Indonesia (IM2 Case)ITU Letter to the President of Indonesia (IM2 Case)
ITU Letter to the President of Indonesia (IM2 Case)
 
Poly Clip Zertificate
Poly Clip ZertificatePoly Clip Zertificate
Poly Clip Zertificate
 
Ejecucion presupuesto 2012_2014
Ejecucion presupuesto 2012_2014Ejecucion presupuesto 2012_2014
Ejecucion presupuesto 2012_2014
 
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, SaylaJanhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
Janhit Humanitarian Magazine 2013 - Raj Saubhag Ashram, Sayla
 
Aplicando lo aprendido con las tic
Aplicando lo aprendido con las ticAplicando lo aprendido con las tic
Aplicando lo aprendido con las tic
 
Cl130
Cl130Cl130
Cl130
 
PAFonteyne_ExtendedCV_2015
PAFonteyne_ExtendedCV_2015PAFonteyne_ExtendedCV_2015
PAFonteyne_ExtendedCV_2015
 
Elastische Skalierbarkeit für Web-Anwendungen
Elastische Skalierbarkeit für Web-AnwendungenElastische Skalierbarkeit für Web-Anwendungen
Elastische Skalierbarkeit für Web-Anwendungen
 
Info mipa p85 lang
Info mipa p85 langInfo mipa p85 lang
Info mipa p85 lang
 
Zanox se instala en España. Sep2003. Revista Estrategias.
Zanox se instala en España. Sep2003. Revista Estrategias. Zanox se instala en España. Sep2003. Revista Estrategias.
Zanox se instala en España. Sep2003. Revista Estrategias.
 
Consigli & Ricette per piccoli gourmet
Consigli & Ricette per piccoli gourmetConsigli & Ricette per piccoli gourmet
Consigli & Ricette per piccoli gourmet
 
Portafolio de Cultura Neuroactiva
Portafolio de Cultura NeuroactivaPortafolio de Cultura Neuroactiva
Portafolio de Cultura Neuroactiva
 
brochure ck line
brochure ck linebrochure ck line
brochure ck line
 
Omam Consultants Presentation
Omam Consultants   PresentationOmam Consultants   Presentation
Omam Consultants Presentation
 
Manejo del embarazo no deseado (1)
Manejo del embarazo no deseado (1)Manejo del embarazo no deseado (1)
Manejo del embarazo no deseado (1)
 
Musica
MusicaMusica
Musica
 
Bits arte y formas geométricas
Bits arte y formas geométricasBits arte y formas geométricas
Bits arte y formas geométricas
 
GKA deel 1 college 9
GKA deel 1 college 9GKA deel 1 college 9
GKA deel 1 college 9
 
Calendario de Actividades en Acapulco
Calendario de Actividades en AcapulcoCalendario de Actividades en Acapulco
Calendario de Actividades en Acapulco
 
Factor 10. Recursos Físicos y Financieros
Factor 10. Recursos Físicos y FinancierosFactor 10. Recursos Físicos y Financieros
Factor 10. Recursos Físicos y Financieros
 

Similar to Spring MVC 3 Restful

SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
Francesco Ierna
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
There is time for rest
There is time for rest There is time for rest
There is time for rest
SoftServe
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
JBug Italy
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Matthew Turland
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Server-side Technologies in Java
Server-side Technologies in JavaServer-side Technologies in Java
Server-side Technologies in Java
Anirban Majumdar
 
RESTEasy
RESTEasyRESTEasy
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Session12 J2ME Generic Connection Framework
Session12 J2ME Generic Connection FrameworkSession12 J2ME Generic Connection Framework
Session12 J2ME Generic Connection Framework
muthusvm
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
Li Yi
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
vikram singh
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...
Timur Shemsedinov
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVC
Alan Dean
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
Neil Ghosh
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
Techglyphs
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
Android and REST
Android and RESTAndroid and REST
Android and REST
Roman Woźniak
 

Similar to Spring MVC 3 Restful (20)

SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
There is time for rest
There is time for rest There is time for rest
There is time for rest
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Server-side Technologies in Java
Server-side Technologies in JavaServer-side Technologies in Java
Server-side Technologies in Java
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Session12 J2ME Generic Connection Framework
Session12 J2ME Generic Connection FrameworkSession12 J2ME Generic Connection Framework
Session12 J2ME Generic Connection Framework
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVC
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Servlet
Servlet Servlet
Servlet
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 

More from knight1128

Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
knight1128
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
knight1128
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
knight1128
 
Jdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicJdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamic
knight1128
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
knight1128
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin
knight1128
 
공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction
knight1128
 
아마존 Aws 서비스_연구
아마존 Aws 서비스_연구아마존 Aws 서비스_연구
아마존 Aws 서비스_연구
knight1128
 
속도체크
속도체크속도체크
속도체크
knight1128
 
구글크롬Os
구글크롬Os구글크롬Os
구글크롬Os
knight1128
 
하이브리드앱
하이브리드앱하이브리드앱
하이브리드앱
knight1128
 
오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유
knight1128
 
Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상
knight1128
 

More from knight1128 (18)

Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토���의 Devops 사례)Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
 
Comet
CometComet
Comet
 
Apache avro
Apache avroApache avro
Apache avro
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Redis
RedisRedis
Redis
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
 
Jdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicJdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamic
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Jdk 7 3-nio2
Jdk 7 3-nio2Jdk 7 3-nio2
Jdk 7 3-nio2
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin
 
공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction
 
아마존 Aws 서비스_연구
아마존 Aws 서비스_연구아마존 Aws 서비스_연구
아마존 Aws 서비스_연구
 
속도체크
속도체크속도체크
속도체크
 
구글크롬Os
구글크롬Os구글크롬Os
구글크롬Os
 
하이브리드앱
하이브리드앱하이브리드앱
하이브리드앱
 
오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유
 
Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상
 

Recently uploaded

Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
Awais Yaseen
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
welrejdoall
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
Sally Laouacheria
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
SynapseIndia
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 

Recently uploaded (20)

Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 

Spring MVC 3 Restful

  • 1. Spring 3 MVC Rest (3.0.5 기준)김용환Knight76 at gmail.comKnight76.tistory.com맛보기
  • 2. 특징REST를 쓰기 위해서 Spring MVC 모델을 그대로 차용, Annotation 이용(Controller)JSR 311을 따르지는 않지만, 대부분의 기능 구현하나의 리소스는 여러 개의 Represenation을 가질 수있도록함 (JSON/XML/ATOM/RSS)브라우저에서 지원하지 않는 PUT & POST 요청을 처리할 수 있음Custom parser 이용 가능UTIL(converter..) 클래스 지원=> REST 관련 Conception만 조금 공부하면 되고, 나머지는 기존 MVC만 알면 되기 까닭에재사용성이 큼
  • 3. Spring 3 Rest 지원#1Annotation 지원 @Controller : MVC@RequestMapping : HTTP 메소드, URI, 헤더 처리@RequestMapping(method=RequestMethod.GET, value="/members", @PathVariable: 메소드 안에서 파라미터와매핑하기 위해서 사용public ModelAndViewgetEmployee(@PathVariable String id) { … } @RequestParam : URL 매개변수 이용@RequestHeader@RequestBody@HttpEntity<T>@ResponseEntity<T> : 정의한대로 response 리턴public @ResponseBody Employee getEmployeeBy(@RequestParam("name") String name, @RequestHeader("Accept") String accept, @RequestBody String body) {…} public ResponseEntity<String> method(HttpEntity<String> entity) {…}
  • 4. Spring 3 Rest 지원 #1Annotation 지원@ResponseStatus@ExceptionHandler
  • 5. Spring 3 Rest 지원 #2ContentNegotiatingViewResolver요청 데이터 포맷에 맞춰 다양한 MIME(미디어 타입) 이나 content type으로 전달 가능ATOM, RSS, XML, JSON, OXM예)http://localhost:8080/fruit/banana.xmlhttp://localhost:8080/fruit/banana.rsshttp://localhost:8080/fruit/banana.htmlAccept : application/xmlAccept : application/jsonAccept : application/html
  • 8. @Controller@Controller@RequestMapping("/restful")public class RestfulController {@RequestMapping(value = "/message/{name}", method = RequestMethod.GET) public String getMessage(@PathVariable String name, ModelMap model) {model.addAttribute("message", name); return "list"; }…}
  • 9. Request Parameter TypeStrong@Controller@RequestMapping("/restful")public class RestfulController { @RequestMapping(value = "/message/{name}", method = RequestMethod.GET) public String getMessage(@PathVariableString name, ModelMap model) {model.addAttribute("message", name); return "list"; }…}
  • 10. @PathVariable@Controller@RequestMapping("/restful")public class RestfulController { @RequestMapping(value = "/message/{name}", method = RequestMethod.GET) public String getMessage(@PathVariable String name, ModelMap model) {model.addAttribute("message", name); return "list"; }…}
  • 11. @ResponseBody@Controller@RequestMapping("/restful")public class RestfulController {@RequestMapping(value = "/messagebody/{message}", method = RequestMethod.GET)@ResponseBodypublic Body getMessageBody(@PathVariable String message, ModelMap model) {Body body = new Body();body.setMessage(message);return body;}…}@XmlRootElement(name = "body")public class Body {@XmlElementprivate String msg;public String getMessage() { return msg;}public void setMessage(String message) { this.msg = message;}}
  • 12. @ResponseStatus@RequestMapping(value = "/exception", method = RequestMethod.GET)public String throwException() { throw new ResourceNotFoundException();}@ExceptionHandler(ResourceNotFoundException.class)@ResponseStatus(value = HttpStatus.BAD_GATEWAY) public void handleNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) {System.out.println("handleNotFoundException:" + ex);}…..class ResourceNotFoundException extends RuntimeException { } $ curl -i localhost:8080/restful/exceptionHTTP/1.1 502 Bad GatewayContent-Length: 0Server: Jetty(6.1.26)결과
  • 13. Rest 방식과 기존 파라미터요청 방식 을 같이 사용가능??@RequestMapping(value = "/test/{name}/id/{id}", method = RequestMethod.GET)public String getString(@PathVariable String name, @PathVariableint id, String email, ModelMap model) {model.addAttribute("message", name);model.addAttribute("id", id);model.addAttribute("email", email); return "test";}가능// test.jsp<html><head></head><body><h1>Test</h1><h3>message : ${message}</h3><h3>email : ${email}</h3></body></html>$ curl http://localhost:8080/restful/test/jaja/id/11?email=aaa@google.com<html><head></head><body> <h1>Test</h1> <h3>message : jaja</h3> <h3>email : aaa@google.com</h3></body></html>결과
  • 14. JSON Payload 요청 #1@Controller@RequestMapping("/comm")@ResponseStatus(value = HttpStatus.ACCEPTED)public class JsonRequestController { @RequestMapping(method = RequestMethod.GET) @ResponseStatus(value=HttpStatus.FOUND) public void sendFruitMessage(@RequestBody Message name) {System.out.println("name : " + name.getName()); return ; }}Spring MVC가 알아서 deserialization을 해줌@XmlRootElement(name = "message")public class Message {@XmlElementprivate String name;public String getName() {return name;} public void setName(String name) { this.name = name; }}
  • 15. JSON Payload 요청 #2결과 : xml <클라이언트>$ curl -i -H "Content-Type: application/xml" -X get -d '<message><name>Kim Yong Hwan</name></message>' localhost:8080/commHTTP/1.1 302 FoundContent-Length: 0Server: Jetty(6.1.26)<서버>name : Kim Yong Hwan결과 : json<클라이언트>$ curl -i -H "Content-Type: application/json" -X get -d '{"name":"Kim Yong Hwan"}' localhost:8080/commHTTP/1.1 302 FoundContent-Length: 0Server: Jetty(6.1.26)<서버>name : Kim Yong Hwan
  • 16. DEMO
  • 17. WEB.XML<web-app id="WebApp_ID" version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><display-name>Spring Web MVC Rest Demo Application</display-name><servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern></servlet-mapping><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value></context-param><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>
  • 18. mvc-dispatcher-servlet.xml<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:component-scan base-package="com.google.controller" /><mvc:annotation-driven /><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /></bean></beans>
  • 19. RestfulController.java@Controller@RequestMapping("/restful")public class RestfulController {@RequestMapping(value = "/message/{name}", method = RequestMethod.GET) public String getMessage(@PathVariable String name, ModelMap model) {model.addAttribute("message", name); return "list"; }@RequestMapping(value = "/command/{id}/content/{content}", method = RequestMethod.GET) public String getCommand(@PathVariable("id") String id, @PathVariable("content") long content, ModelMap model) {model.addAttribute("id", id);model.addAttribute("content", content); return "command"; }@RequestMapping(value = "/link/{id}", method = RequestMethod.DELETE) public String deleteLink(@PathVariable("id") String id, ModelMap model) {model.addAttribute("id", id); return "delete"; }}
  • 20. JSP 소스// WEB-INF/pages/list.jsp<html><body><h1>Spring MVC Restful Test</h1><h3>message : ${message}</h3></body></html>// WEB-INF/pages/command.jsp<html><body><h1>Spring MVC Restful Test</h1> <h3>command id : ${id}</h3><h3>content : ${content}</h3></body></html>// WEB-INF/pages/delete.jsp<html><body><h1>Spring MVC Restful Test</h1><h3>deleted id : ${id}</h3></body></html>
  • 22. 결과 (리눅스/Cygwin)curl -X DELETE http://localhost:8080/restful/link/1 curl -X DELETE http://localhost:8080/restful/message/3
  • 24. Content NegotiationHTTP 1.1 스펙에서 정의의미media type, 언어, 문자집합, 인코딩 등에 대해 브라우저가 제공한 선호도에 따라 자원의 가장 적합한 표현을 선택. 불완전한 협상 정보를 보내는 브라우저의 요청을 지능적으로 처리하는 기능일반적으로 다른 프로토콜을 쓰려면, request의 “type” 파라미터를 확인하고, 이에 맞는 marshalling정보를 전달해야 한다.트위터API가 이렇게 사용되고 있음Spring MVC에서는 한번에 해결해주는 클래스 사용 ContentNegotiatingViewResolver
  • 25. DEMO
  • 26. FruitController@Controller@RequestMapping("/fruit")public class FruitController{ @RequestMapping(value="{fruitName}", method = RequestMethod.GET) public String getFruit(@PathVariable String fruitName, ModelMap model) { Fruit fruit = new Fruit(fruitName, 1000);model.addAttribute("model", fruit); return "listfruit"; }}
  • 27. Fruit@XmlRootElement(name = "fruit")public class Fruit {String name;intquality;public Fruit() {}public Fruit(String name, int quality) { this.name = name;this.quality = quality;}@XmlElementpublic void setName(String name) {this.name = name;}@XmlElementpublic void setQuality(int quality) {this.quality = quality;}}
  • 28. mvc-dispatcher-servlet.xml<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"><map> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> <entry key="rss" value="application/rss+xml" /></map> </property> <property name="defaultViews"><list> <!-- JSON View --> <beanclass="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> </bean> <!-- RSS View --> <bean class="com.google.rss.RssFeedView" /> <!-- JAXB XML View --> <bean class="org.springframework.web.servlet.view.xml.MarshallingView"><constructor-arg><bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="classesToBeBound"><list> <value>com.google.bean.Fruit</value></list> </property></bean></constructor-arg> </bean> </list> </property> <property name="ignoreAcceptHeader" value="true" /></bean><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="order" value="2" /><property name="prefix" value="/WEB-INF/pages/" /><property name="suffix" value=".jsp" /></bean>
  • 29. 결과$ curl -H 'Accept: application/xml' localhost:8080/fruit/banana.xml<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fruit><name>banana</name><quality>1000</quality></fruit>$ curl -H 'Accept: application/rss'localhost:8080/fruit/banana.rss<?xml version="1.0" encoding="UTF-8"?><rssxmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0"> <channel> <title>Sample Title</title> <link>http://google.com</link> <description>Sample Description</description> <item> <link>http://www.google.com</link> <content:encoded>banana1000</content:encoded> <author>Test</author> </item> </channel></rss>$ curl -H 'Accept: application/json' localhost:8080/fruit/banana.json{"model":{"quality":1000,"name":"banana"}}
  • 30. Demo에서 @XmlElement사용시 유의할 점Set메소드를 사용하려면, 다음과 같이 한다. 클래스의 멤버 필드에서 @XmlElement를 정의할 때는 set 메소드를 사용하지 않는다. @XmlRootElement(name = "fruit")public class Fruit { private String name; private int quality;@XmlElement public void setBody(Body body) {this.body= body; } public String getName() { return name; }@XmlElement public void setQuality(int quality) {this.quality= quality; } public intgetQuality() { return quality; }…}@XmlRootElement(name = "fruit")public class Fruit {@XmlElement private String name;@XmlElement private int quality; public String getName() { return name; } public intgetQuality() { return quality; }…}JAXB에서 property를 읽을 때, 잘 사용해야 하는 구조
  • 31. Demo에서 @XmlElement사용시유의할 점Body 클래스앞에@XmlRootElement선언이 되어 있으면, Fruit 클래스 에서 @XmlElement를 사용하지 않아도 된다.@XmlRootElement(name = "body")public class Body { @XmlElement private String msg; // set/get accessory ….}@XmlRootElement(name = "fruit")public class Fruit {@XmlElement private String name;@XmlElement private int quality; private Body body; public String getName() { return name; } public intgetQuality() { return quality; }…}
  • 33. 웹 브라우져 제약 #1GET/POST만 쓸 수 있는 웹 브라우져가 있을 수 있다. PUT과 DELETE 을 쓰기 위해서는 trick을 써야 한다.HiddenHttpMethodFilter이용Web.xml  <filter>        <filter-name>httpMethodFilter</filter-name>        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>    </filter>        <filter-mapping>        <filter-name>httpMethodFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>
  • 34. 웹 브라우져 제약 #2// spring mvc form tag<form:form method="delete"> <p class="submit"><input type="submit" value="Delete Pet"/></p> </form:form>@RequestMapping(method = RequestMethod.DELETE)public String deletePet(@PathVariableintownerId, @PathVariableintpetId) {this.clinic.deletePet(petId); return "redirect:/owners/" + ownerId;}아마도 예전처럼 내부적으로 name=“_method” value=“Delete” 하는 형태로 전달하고, Spring 서버는 이 정보를 바탕으로 구현 했을 것으로 예상<form action="POST">  <input type="hidden" id="_method" value="PUT"></form>
  • 35. PUT/DELETE in HTMLHTML version 4 과 XHTML 1에서는 HTML form안의 HTTP 요청은 GET과 POST 방식만 허용. 그동안put/delete 메소드를 사용하려면, XMLHttpRequest를 이용하였음HTTP상에서는 ok!HTML5에서 put/delete는 사용하지 못한다고 나와 있음http://www.w3.org/TR/html5-diff/Using PUT and DELETE as HTTP methods for the form element is no longer supported.참고
  • 36. 클라이언트 API : RestTemplate
  • 37. 클라이언트 APIApache Commons의 HttpClient대신 쉽게 사용할 수 있는 RestTemplate구성<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"><property name="messageConverters"> <list> <ref bean="marshallingConverter" /> <ref bean="atomConverter" /> <ref bean="jsonConverter" /> </list></property></bean>
  • 38. 클라이언트 APIXML 요청HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_XML);HttpEntity<String> entity = new HttpEntity<String>(headers);ResponseEntity<EmployeeList> response = restTemplate.exchange("http://localhost:8080/rest/service/emps", HttpMethod.GET, entity, EmployeeList.class);EmployeeListingemployees = response.getBody();// handle the employees
  • 39. 클라이언트 API새직원포스팅/ 삭제Employee newEmp = new Employee(11, “tguest", “tguest@google.com");HttpEntity<Employee> entity = new HttpEntity<Employee>(newEmp);restTemplate.put( "http://localhost:8080/rest/service/emp/{id}", entity, "99");restTemplate.delete( "http://localhost:8080/rest/service/emp/{id}", "99");
  • 42. RestTemplate예제Map<String, String> vars = new HashMap<String, String>();vars.put("id", "111");vars.put("content", "222");RestTemplaterestTemplate = new RestTemplate();String result = restTemplate.getForObject("http://localhost:8080/restful/command/{id}/content/{content}", String.class, vars);System.out.println("result : " + result);result : <html><body><h1>Spring MVC Restful Test</h1> <h3>command id : 111</h3><h3>content : 222</h3></body></html>결과