Вы находитесь на странице: 1из 13

Web- RESTful-

Spring 3 MVC HttpMessageConverter



-
IBM

04.07.2011

Spring, Java Platform Enterprise


Edition (Java EE),
(Representational State Transfer REST) --
(Model-View-Controller MVC). Web- RESTful
, . ,
HttpMessageConverter.
, RestTemplate HttpMessageConverter
. , ,
Spring Web- RESTful-,
, ATOM Feed, XML JavaScript Object Notation (JSON).

" Web- RESTful Spring 3" (. )


Web- RESTful Sping.
, ContentNegotiatingViewResolver
, Web- RESTful.

HttpMessageConverter, RestTemplate
HttpMessageConverter .

REST Spring MVC


Spring ( ),
Web- RESTful.
@Controller

@Controller, ,
MVC HTTP-.
Copyright IBM Corporation 2011
Web- RESTful-
Spring 3 MVC HttpMessageConverter


1 13

developerWorks

ibm.com/developerWorks/ru/

@RequestMapping

@RequestMapping, ,
HTTP-, URI HTTP-.
REST Spring.
method HTTP-.
:
@RequestMapping(method=RequestMethod.GET, value="/emps",
headers="Accept=application/xml, application/json")

@PathVariable

@PathVariable URI
.
:
@RequestMapping(method=RequestMethod.GET, value="/emp/{id}")
public ModelAndView getEmployee(@PathVariable String id) { }


@RequestParam, URL- .
@RequestHeader, HTTP- .
@RequestBody, HTTP- .
@ResponseBody,
HTTP-.
HttpEntity<T> ,
.
ResponseEntity<T>, HTTP-
.
:
public @ResponseBody Employee getEmployeeBy(@RequestParam("name")
String name, @RequestHeader("Accept") String accept, @RequestBody String body) {}
public ResponseEntity<String> method(HttpEntity<String> entity) {}

Spring (. )
, .


MIME-
RESTful Web-. ,
URI HTTP-
. URI URI
.
Web- RESTful-
Spring 3 MVC HttpMessageConverter

2 13

ibm.com/developerWorks/ru/

developerWorks

" Web- RESTful Spring 3" (. )


ContentNegotiatingViewResolver,
URI ( ).
, ContentNegotiatingViewResolver
.

HttpMessageConverter @ResponseBody.
View.

HttpMessageConverter
HTTP- , ..
. Spring
String ( Java-).
Spring / ?
HttpMessageConverter. Spring ,
. 1 .

1. HttpMessageConverter
...

...

StringHttpMessageConverter

/ .
- text/*
Content-Type, text/plain.

FormHttpMessageConverter

/ .
- pplication/x-www-form-urlencoded
MultiValueMap<String,String>.

MarshallingHttpMessageConverter

/ XML- /
Spring. -
application/xml.

MappingJacksonHttpMessageConverter

/ JSON- Jackson's
ObjectMapper. - application/
json.

AtomFeedHttpMessageConverter

/ ATOM ROME Feed API.


- application/atom+xml.

RssChannelHttpMessageConverter

/ RSS ROME Feed API.


- application/rss+xml.

Web- RESTful
, Web- RESTful,
. ,
, " Web- RESTful
Spring 3" (. ). .
-, HttpMessageConverter.
, HttpMessageConverter
Web- RESTful-
Spring 3 MVC HttpMessageConverter

3 13

developerWorks

ibm.com/developerWorks/ru/

-. - JSON,
ATOM XML.

JSON
. JSON - ,
. 1 ,
JSON.

1. HttpMessageConverter rest-servlet.xml
<bean class="org.springframework.web.servlet.mvc.annotation
.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
<ref bean="marshallingConverter" />
<ref bean="atomConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json
.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>

.
MappingJacksonHttpMessageConverter JSON
. Jackson ObjectMapper
JSON JavaBean, Jackson JAR-
classpath.
org.codehaus.jackson.jar
org.codehaus.jackson.mapper.jar
JSON.
2 .

2. JSON-, EmployeeController
@RequestMapping(method=RequestMethod.GET, value="/emp/{id}",
headers="Accept=application/json")
public @ResponseBody Employee getEmp(@PathVariable String id) {
Employee e = employeeDS.get(Long.parseLong(id));
return e;
}
@RequestMapping(method=RequestMethod.GET, value="/emps",
headers="Accept=application/json")
public @ResponseBody EmployeeListinggetAllEmp() {
List<Employee> employees = employeeDS.getAll();
EmployeeListinglist = new EmployeeList(employees);
return list;
}

Web- RESTful-
Spring 3 MVC HttpMessageConverter

4 13

ibm.com/developerWorks/ru/

developerWorks

@ResponseBody ,
(Employee EmployeeList) ,
MappingJacksonHttpMessageConverter JSON.
HttpMessageConverter @ResponseBody
, Spring View,
ContentNegotiatingViewResolver.
CURL REST- Firefox .
HTTP-: Accept=application/json. 3
JSON.

3. JSON- getEmp() getAllEmp()


Response for /rest/service/emp/1
{"id":1,"name":"Huang Yi Ming","email":"huangyim@cn.ibm.com"}
Response for /rest/service/emps
{"count":2,
"employees":[
{"id":1,"name":"Huang Yi Ming","email":"huangyim@cn.ibm.com"},
{"id":2,"name":"Wu Dong Fei","email":"wudongf@cn.ibm.com"}
]}

XML
Spring MarshallingHttpMessageConverter
XML (OXM). JAXB 2
/ . 4 .

4. MarshallingHttpMessageConverter
<bean id="marshallingConverter"
class="org.springframework.http.converter.xml
.MarshallingHttpMessageConverter">
<constructor-arg ref="jaxbMarshaller" />
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="jaxbMarshaller"
class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>dw.spring3.rest.bean.Employee</value>
<value>dw.spring3.rest.bean.EmployeeList</value>
</list>
</property>
</bean>

, JAXB 2 java.util.List<T>
XML. -
. " Web- RESTful Spring 3" (.
) ,
JAXB-.
Web- RESTful-
Spring 3 MVC HttpMessageConverter

5 13

developerWorks

ibm.com/developerWorks/ru/

, ?
2. , .
- Accept:
headers=Accept=application/json, application/xml

(JSON XML).
5 application/xml.

5. XML- getEmp() getAllEmp()


Response for /rest/service/emp/1
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<email>huangyim@cn.ibm.com</email>
<id>1</id>
<name>Huang Yi Ming</name>
</employee>
Response for /rest/service/emps
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
<count>2</count>
<employee>
<email>huangyim@cn.ibm.com</email>
<id>1</id>
<name>Huang Yi Ming</name>
</employee>
<employee>
<email>wudongf@cn.ibm.com</email>
<id>2</id><name>Wu Dong Fei</name>
</employee>
</employees>

ATOM
ATOM - Web- RESTful.
Atom Atom,
( ) , . atom:feed.
ATOM Publish Protocol (APP),
. ( ATOM APP- . .
.)
AtomFeedHttpMessageConverter
ATOM, ROME ATOM API. JAR-
sun.syndication.jar classpath. 6 .

6. AtomFeedHttpMessageConverter
<bean id="atomConverter"
class="org.springframework.http.converter.feed
.AtomFeedHttpMessageConverter">
<property name="supportedMediaTypes" value="application/atom+xml" />
</bean>

7 , ATOM .
Web- RESTful-
Spring 3 MVC HttpMessageConverter

6 13

ibm.com/developerWorks/ru/

developerWorks

7. getEmpFeed() EmployeeController & AtomUtil


@RequestMapping(method=RequestMethod.GET, value="/emps",
headers="Accept=application/atom+xml")
public @ResponseBody Feed getEmpFeed() {
List<Employee> employees = employeeDS.getAll();
return AtomUtil.employeeFeed(employees, jaxb2Mashaller);
}
public static Feed employeeFeed(
List<Employee> employees, Jaxb2Marshaller marshaller) {
Feed feed = new Feed();
feed.setFeedType("atom_1.0");
feed.setTitle("Employee Atom Feed");
List<Entry> entries = new ArrayList<Entry>();
for(Employee e : employees) {
StreamResult result = new StreamResult(
new ByteArrayOutputStream());
marshaller.marshal(e, result);
String xml = result.getOutputStream().toString();
Entry entry = new Entry();
entry.setId(Long.valueOf(e.getId()).toString());
entry.setTitle(e.getName());
Content content = new Content();
content.setType(Content.XML);
content.setValue(xml);
List<Content> contents = new ArrayList<Content>();
contents.add(content);
entry.setContents(contents);
entries.add(entry);
}
feed.setEntries(entries);
return feed;
}

, :
GetEmpFeed() URI, getAllEmp(),
Accept.
employeeFeed() Employee XML,
<content> .
8 application/atom+xml URI /
rest/service/emps.

8. /rest/service/emps application/atom
+xml
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Employee Atom Feed</title>
<entry>
<title>Huang Yi Ming</title>
<id>1</id>
<content type="xml">
<employee>
<email>huangyim@cn.ibm.com</email>
<id>1</id>

Web- RESTful-
Spring 3 MVC HttpMessageConverter

7 13

developerWorks

ibm.com/developerWorks/ru/

<name>Huang Yi Ming</name>
</employee>
</content>
</entry>
<entry>
<title>Wu Dong Fei</title>
<id>2</id>
<content type="xml">
<employee>
<email>wudongf@cn.ibm.com</email>
<id>2</id>
<name>Wu Dong Fei</name>
</employee>
</content>
</entry>
</feed>

POST, PUT DELETE


HTTP- GET. 9
POST, PUT DELETE.

9. POST, PUT DELETE EmployeeController


@RequestMapping(method=RequestMethod.POST, value="/emp")
public @ResponseBody Employee addEmp(@RequestBody Employee e) {
employeeDS.add(e);
return e;
}
@RequestMapping(method=RequestMethod.PUT, value="/emp/{id}")
public @ResponseBody Employee updateEmp(
@RequestBody Employee e, @PathVariable String id) {
employeeDS.update(e);
return e;
}
@RequestMapping(method=RequestMethod.DELETE, value="/emp/{id}")
public @ResponseBody void removeEmp(@PathVariable String id) {
employeeDS.remove(Long.parseLong(id));
}

@RequestBody addEmp() updateEmp().


HTTP- ,
HttpMessageConverter.
RestTemplate REST-.

RestTemplate REST
" Web- RESTful Spring 3" (. )
, CURL REST- REST-.
Jakarta Commons HttpClient
( ). Spring REST RestTemplate.
Spring, JdbcTemplate JmsTemplate.
Web- RESTful-
Spring 3 MVC HttpMessageConverter

8 13

ibm.com/developerWorks/ru/

developerWorks

HttpMessageConverter.
.
RestTemplate

RestTemplate
10 RestTemplate.
.

10. 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>

,
. RestTemplate ,
:

exchange: HTTP-
getForObject: HTTP- GET .
postForObject: HTTP- POST .
put: HTTP- PUT .
delete: HTTP- DELETE URI.


RestTemplate.
RestTemplate API (. ),
API.
11 , , .
MarshallingHttpMessageConverter,
.
-.

11. XML-
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();
// employees

Web- RESTful-
Spring 3 MVC HttpMessageConverter

9 13

developerWorks

ibm.com/developerWorks/ru/

12 POST.
AddEmp() - application/
xml application/json.

12. POST
Employee newEmp = new Employee(99, "guest", "guest@ibm.com");
HttpEntity<Employee> entity = new HttpEntity<Employee>(newEmp);
ResponseEntity<Employee> response = restTemplate.postForEntity(
"http://localhost:8080/rest/service/emp", entity, Employee.class);
Employee e = response.getBody();
// employee

13 , PUT.
- ({id}) URI .

13. PUT
Employee newEmp = new Employee(99, "guest99", "guest99@ibm.com");
HttpEntity<Employee> entity = new HttpEntity<Employee>(newEmp);
restTemplate.put(
"http://localhost:8080/rest/service/emp/{id}", entity, "99");

14 ,
DELETE.

14. DELETE
restTemplate.delete(
"http://localhost:8080/rest/service/emp/{id}", "99");

HttpMessageConverter, Spring 3.
, .
,
HttpMessageConverter ,
ContentNegotiatingViewResolver " Web RESTful Spring 3".

Web- RESTful-
Spring 3 MVC HttpMessageConverter

10 13

ibm.com/developerWorks/ru/

developerWorks

src_code.zip

11

Web- RESTful-
Spring 3 MVC HttpMessageConverter

11 13

developerWorks

ibm.com/developerWorks/ru/

Build RESTful web services with the Spring 3 MVC HttpMessageConverter


feature (EN).
Web- RESTful Spring 3
(developerWorks, 2010 , EN) Web-
RESTful Spring.
REST
.
Spring MVC Showcase,
, . ,
.
Spring 3.
RestTemplate API.
JAXB Reference Implementation Project.
ROME - Java- Atom/RSS, Java
.
ATOM.
DeveloperWorks Atom Publishing Protocol
( 2006 .), ,
(EN).
Jackson - JSON- .

Spring.
Jackson.
IBM
IBM SOA Sandbox,
DB2, Lotus, Rational,
Tivoli WebSphere.

developerWorks, Web-.
Web- Web.
Web 2.0
.
Web-, developerWorks.

Web- RESTful-
Spring 3 MVC HttpMessageConverter

12 13

ibm.com/developerWorks/ru/

developerWorks



(Yi Ming Huang) - - China Development Lab,
Mashup- Lotus. Web-
. REST, OSGi Spring.

Copyright IBM Corporation 2011


(www.ibm.com/legal/copytrade.shtml)

(www.ibm.com/developerworks/ru/ibm/trademarks/)

Web- RESTful-
Spring 3 MVC HttpMessageConverter

13 13