2013년 4월 4일 목요일

Spring3를 이용하여 RESTFul web service 생성하기 - XML, ATOM

Restful 웹 서비스 Build

이전 시간에는 JSON 타입으로  변환하는 것을 공부했다.
이번 시간은 XML과 ATOM 타입으로 변환하는 것을 공부하려고 한다.

XML

Spring3의 내장 변환기인 MarshallingHttpMessageConverter는 Object와 XML 사이에 매핑하는데 사용한다.

==> 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>jini.web.study.bean.User</value>
              <value>jini.web.study.bean.UserList</value>
         </list>
    </property>
</bean>
--------------------------------------------------

앞서 공부한 소스 내용 중 @RequestBody Annotation 속성에서 headers="Accept=application/json, application/xml 을 추가만 하면된다.

ATOM Feed

==> AtomFeedHttpMessageConverter 구성

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


==> TestController에서 정의된  ATOM Feed 요청 처리

--------------------------------------------------
@RequestMapping(method=RequestMethod.GET, value="/users"headers="Accept=application/atom+xml")

public @ResponseBody Feed getUsersFeed() {    
    List<User> users = userDao.getAll();   
    return AtomUtil.employeeFeed(users, jaxb2Mashaller);



public static Feed userFeed(
List<User> users, Jaxb2Marshaller marshaller) {

    Feed feed = new Feed();

    feed.setFeedType("atom_1.0");

    feed.setTitle("Employee Atom Feed");

                       

    List<Entry> entries = new ArrayList<Entry>();
    for(User e : users) {
        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;
}
--------------------------------------------------
  • getUserFeed() method는 앞선 JSON 코드에서의 getAllUsers()와 동일한 URI로 매핑되지만, header에서 Accept 항목이 다르다.
  • userFeed() method를 통해 User Object를 XML로 변환하고 이를 Feed 항목의 content 요소로 추가하는 것을 볼 수 있다.
끝!!


댓글 없음:

댓글 쓰기