스프링 3.0 & RESTful

    백기선, 김성윤
봄싹 즐겨찾기 서비스
To Do
•   링크   등록
•   링크   목록 조회
•   링크   조회
•   링크   수정
•   링크   삭제
즐겨찾기 서비스 URL
작업           URL            Method
목록 조회        /link          GET
추가 (폼)       /link/form     GET
추가 (폼 서브밋)   /link          POST
뷰            /link/1        GET
수정 (폼)       /link/1/form   GET
수정 (폼 서브밋)   /link/1        PUT
삭제           /link/1        DELETE
주요 기술 :: 스프링 3.0 @MVC
•   @RequestMapping
•   @PathVariable
•   hiddenMethodFilter
•   스프링 form 태그
•   ContentsNegotiatingViewResolver
@RequestMapping
@RequestMapping(value = ”/link/{id}", method = RequestMethod.DELETE)
  public String delete(@PathVariable int id){
    postService.delete(id);
    return ”/link";
  }



• DefaultAnnotationHandlerMapping이
  @RequestMapping 정보를 참조해서 핸들
  러 찾아줌.
@PathVariable
 @RequestMapping(value = "/link/{id}", method = RequestMethod.GET)
  public String view(@PathVariable int id, Model model){
     model.addAttribute(”link", linkService.get(id));
     return ”link/view";
  }



• /link/1 => /link/{id}
• 기본값 설정 가능
hiddenMethodFilter
<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>

• 기본값: _method
스프링 form 태그
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


 • form 태그 사용하면 PUT, DELETE 사용시
   자동으로 히든 파라미터로 값 넘겨줌.
<form:form commandName=”link" action=”/link/${link.id}" method="PUT">


<form:form action=”/link/${link.id}" method="DELETE">
ContentsNegotiatingViewResolver
         이게 없다면…
  if ("xml".equals(req.getParameter("type"))) {
    return new ModelAndView(helloMarshallingView, model);
  }
  else {
    return new ModelAndView("/WEB-INF/view/hello.jsp", model);
  }
ContentsNegotiatingViewResolver
         이게 있다면?
ContentsNegotiatingViewResolver
          동작 방식
1. 미디어 타입 결정

2. 뷰 후보 선정

3. 최종 뷰 결정
1. 미디어 타입 결정
1. URL 확장자로 결정
 –   /book.json


2. 요청 파라미터로 결정
 –   /book?format=json


3. Access 헤더 정보로 결정

4. defaultContentType 속성 값 사용.
2. 뷰 후보 선정
1. viewResolvers 미사용시: 서블릿 콘텍스
   트에 등록된 모든 ViewResolver 사용해서
   뷰 후보 선정

2. viewResolvers 사용시: 모든 뷰 리졸버가
   돌려주는 뷰를 후보 목록에 추가

3. defaultView 속성에 설정한 뷰는 무조건
   후보 목록에 추가
3. 최종 뷰 결정
• 미디어 타입과 뷰 목록 비교해서 뷰 결정
 – 뷰의 contents-type과 미디어 타입 비교


• 예제
 – 미디어 타입은 JSON
 – 뷰 후보: JSON 뷰, JSTL 뷰, XML 뷰
 – 결과: JSON뷰 사용
RestTemplate
• Spring 3.0 M2 추가됨.

• Spring’s Template series와 비슷한 형태
 (JdbcTemplate, JmsTemplate ... )

• RESTful 스타일 URL 지원.

• HTTP access 단순화.

• 사용자 정의 콜백 및 결과 추출 클래스 지원.
RestTemplate Hierarchy
RestTemplate methods

HTTP method    RestTemplate methods
GET            getForObject(…)
               getForEntity(…)
POST           postForLocation(…)
               postForObject(…)
PUT            put(…)
DELETE         delete(…)
HEAD           headForHeaders(…)
OPTIONS        optionForAllow(…)
HttpRequests

 SimpleClientHttpRequest
  ( java.net. HttpURLConnection)


CommonsClientHttpRequest
  ( jakarta Commons HttpClient)


 사용자 정의 HttpRequest
HttpMessageConverters
   ByteArray       • application/octet-stream

     String        • text/plain

    Resource       • resource file type

     Source        • text/xml or application/xml

XmlAwareForm       • text/xml or application/xml

Jaxb2RootElement   • text/xml or application/xml

MappingJackson     • application/json

   AtomFeed        • application/atom+xml

   RssChannel      • application/rss+xml
RestTemplate – 사용전
String uri = "http://example.com/hotels/1/bookings";
PostMethod post = new PostMethod(uri);
String request = // create booking request content
post.setRequestEntity(new StringRequestEntity(request));
httpClient.executeMethod(post);
if (HttpStatus.SC_CREATED == post.getStatusCode()) {
    Header location = post.getRequestHeader("Location");
    if (location != null) {
        System.out.println(location.getValue());
    }
}
RestTemplate – 사용후

String uri = "http://example.com/hotels/{id}/bookings";
RestOperations restTemplate = new RestTemplate();
Booking booking = // create booking object
URI location = restTemplate.postForLocation(uri, booking, “1”);
System.out.println(location);
Authentication


Basic Authentication
• CommonsClientHttpRequest


Open Authorization(OAuth)
• 미지원 (3.1M1 Fix 예정)
RestTemplate @ Twitter RESTful

스프링 3.0 & RESTful

  • 1.
    스프링 3.0 &RESTful 백기선, 김성윤
  • 2.
  • 3.
    To Do • 링크 등록 • 링크 목록 조회 • 링크 조회 • 링크 수정 • 링크 삭제
  • 4.
    즐겨찾기 서비스 URL 작업 URL Method 목록 조회 /link GET 추가 (폼) /link/form GET 추가 (폼 서브밋) /link POST 뷰 /link/1 GET 수정 (폼) /link/1/form GET 수정 (폼 서브밋) /link/1 PUT 삭제 /link/1 DELETE
  • 5.
    주요 기술 ::스프링 3.0 @MVC • @RequestMapping • @PathVariable • hiddenMethodFilter • 스프링 form 태그 • ContentsNegotiatingViewResolver
  • 6.
    @RequestMapping @RequestMapping(value = ”/link/{id}",method = RequestMethod.DELETE) public String delete(@PathVariable int id){ postService.delete(id); return ”/link"; } • DefaultAnnotationHandlerMapping이 @RequestMapping 정보를 참조해서 핸들 러 찾아줌.
  • 7.
    @PathVariable @RequestMapping(value ="/link/{id}", method = RequestMethod.GET) public String view(@PathVariable int id, Model model){ model.addAttribute(”link", linkService.get(id)); return ”link/view"; } • /link/1 => /link/{id} • 기본값 설정 가능
  • 8.
    hiddenMethodFilter <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> • 기본값: _method
  • 9.
    스프링 form 태그 <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %> • form 태그 사용하면 PUT, DELETE 사용시 자동으로 히든 파라미터로 값 넘겨줌. <form:form commandName=”link" action=”/link/${link.id}" method="PUT"> <form:form action=”/link/${link.id}" method="DELETE">
  • 10.
    ContentsNegotiatingViewResolver 이게 없다면… if ("xml".equals(req.getParameter("type"))) { return new ModelAndView(helloMarshallingView, model); } else { return new ModelAndView("/WEB-INF/view/hello.jsp", model); }
  • 11.
  • 12.
    ContentsNegotiatingViewResolver 동작 방식 1. 미디어 타입 결정 2. 뷰 후보 선정 3. 최종 뷰 결정
  • 13.
    1. 미디어 타입결정 1. URL 확장자로 결정 – /book.json 2. 요청 파라미터로 결정 – /book?format=json 3. Access 헤더 정보로 결정 4. defaultContentType 속성 값 사용.
  • 14.
    2. 뷰 후보선정 1. viewResolvers 미사용시: 서블릿 콘텍스 트에 등록된 모든 ViewResolver 사용해서 뷰 후보 선정 2. viewResolvers 사용시: 모든 뷰 리졸버가 돌려주는 뷰를 후보 목록에 추가 3. defaultView 속성에 설정한 뷰는 무조건 후보 목록에 추가
  • 15.
    3. 최종 뷰결정 • 미디어 타입과 뷰 목록 비교해서 뷰 결정 – 뷰의 contents-type과 미디어 타입 비교 • 예제 – 미디어 타입은 JSON – 뷰 후보: JSON 뷰, JSTL 뷰, XML 뷰 – 결과: JSON뷰 사용
  • 17.
    RestTemplate • Spring 3.0M2 추가됨. • Spring’s Template series와 비슷한 형태 (JdbcTemplate, JmsTemplate ... ) • RESTful 스타일 URL 지원. • HTTP access 단순화. • 사용자 정의 콜백 및 결과 추출 클래스 지원.
  • 18.
  • 19.
    RestTemplate methods HTTP method RestTemplate methods GET getForObject(…) getForEntity(…) POST postForLocation(…) postForObject(…) PUT put(…) DELETE delete(…) HEAD headForHeaders(…) OPTIONS optionForAllow(…)
  • 20.
    HttpRequests SimpleClientHttpRequest ( java.net. HttpURLConnection) CommonsClientHttpRequest ( jakarta Commons HttpClient) 사용자 정의 HttpRequest
  • 21.
    HttpMessageConverters ByteArray • application/octet-stream String • text/plain Resource • resource file type Source • text/xml or application/xml XmlAwareForm • text/xml or application/xml Jaxb2RootElement • text/xml or application/xml MappingJackson • application/json AtomFeed • application/atom+xml RssChannel • application/rss+xml
  • 22.
    RestTemplate – 사용전 Stringuri = "http://example.com/hotels/1/bookings"; PostMethod post = new PostMethod(uri); String request = // create booking request content post.setRequestEntity(new StringRequestEntity(request)); httpClient.executeMethod(post); if (HttpStatus.SC_CREATED == post.getStatusCode()) { Header location = post.getRequestHeader("Location"); if (location != null) { System.out.println(location.getValue()); } }
  • 23.
    RestTemplate – 사용후 Stringuri = "http://example.com/hotels/{id}/bookings"; RestOperations restTemplate = new RestTemplate(); Booking booking = // create booking object URI location = restTemplate.postForLocation(uri, booking, “1”); System.out.println(location);
  • 24.
    Authentication Basic Authentication • CommonsClientHttpRequest OpenAuthorization(OAuth) • 미지원 (3.1M1 Fix 예정)
  • 25.