Spring 4.x Web
Application Overview
최 신 웹 트 렌 드 를 따 르 는 스 프 링 더 듬 기
발 표 자 소 개
•이 름 : 김 지 헌 (== honeymon)
­ ihoneymon@gmail.com
­ http://honeymon.io
­ 이 노 트 리 (http://innotree.com) 근 무
­ KSUG 일 꾼 단 소 속 잡무 수 행
­ 개 발 자 …
­ 종 합레 저 스 포 츠 인 을 표 방
Spring framework
● 2003, JDK 1.4
● https://spring.io/blog/2004/03
/24/spring-framework-1-0-
final-released
● Annotation, REST, SPAs,
WebSocket 가 요 구 되 기 전
Programming Model Version
@Controller 2.5(2007)
REST 3.0(2009)
Async HTTP 3.2(2012)
WebSocket 4.0(2013)
Programming Model
스 프 링 프 레 임 워 크 의
성 공 포 인 트
간결 하 고 , 깔 끔 하 고 , 안 정 적 인 설 계
확장의 자 유 로 움
HTTP, REST, Messaging
등 다 양 한 지 원
강력 한 커 뮤 니 티 !!
http://ksug.org
변 화하 는 환경 에 따 라 끊 임 없 이 진 화!
?WHY
@Controller method
• @InitBinder
• @ModelAttribute
• @RequestMapping
• @ExceptionHandler
@RestController
@Controller
public class MyController {
@RequestMapping @ResponseBody
public Foo handleFoo() {
}
@RequestMapping @ResponseBody
public Boo handleBoo() {
}
}
@RestController
public class MyController {
@RequestMapping
public Foo handleFoo() {
}
@RequestMapping
public Boo handleBoo() {
}
}
@RestController = @Controller + @ResponseBody
@ControllerAdvice
• InitBinder
• ModelAttribute
• ExceptionHandler
@ControllerAdvice
• @ControllerAdvice
• @ControllerAdvice(annotations=RestController.class)
• @ControllerAdvice(basePackages="org.ksug")
• @ControllerAdvice(assignableTypes=
{MyController.class})
ResponseEntityExceptionHandler - v3.2
• @ControllerAdvice를 함께 사 용 하 는 예 외
처 리 추 상 클 래 스
• Spring MVC 예 외 처 리
• REST API 친 화적 임
ResponseBodyAdvice
• @ControllerAdvice와 함께 사 용 하 는 인 터 페 이 스
• v4.1에 추 가 됨
• 컨 트 롤 러 에 서 반 환된 응 답 결 과를
HttpMessageConverter가 다 루 기 전 에
작 업
RequestBodyAdvice + v4.2
Jackson 이 야 기
• Jackson: JSON & XML 조 작
• Jackson2ObjectMapperBuilder 를 이 용 해 서
ObjectMapper 인 스 턴 스 를 생 성
• LastestJackon integration improvements
in spring
– @JsonView: Jackson's Serialization View
– JSONP: @ResponseEntity & ResponseEntity
@RequestMapping
• java.util.Optional(JDK 8) 지 원
• ResponseEntity/RequestEntity buider-style method
• MvcUriComponentBuilder를 사 용 하 여 다 른 컨 트 롤 러 의 메
서 드 를 호 출 할 수 있 는 URI 생 성
• @ModelAttribute 사 이 의 의 존 성 부 여
정 적 자 원 지 원
• ResourceHttpRequesthandler < 4.1
• ResourceResolver, ResourceTransformer, ResourceUrlProvider 4.1+
• 컨 텐 츠 기 반 해 시 를 가 진 Versioned URL
– e.g. "/css/font-awesome.min-7fbe76cdac.css"
• 보 다 자 세 한 사 항은 !!
– Resource Handling Spring MVC 4.1 - SpringOne 2014
– Resource handling Spring MVC - Adieu 2014, 봄 싹(박 용 권 )
Groovy markup template
• HTML 템 플 릿 용 DSL을 Groovy 로 컴 파일
• Groovy 의 강력 한 힘 으 로 !
• See GroovyMarkup View
Javascript Templating + v4.2
MVC 설 정
• ViewResolver 등 록 지 원
• ViewController 설 정
• Path matching 설 정
비 동 기 HTTP 요 청
• Servlet 3.0+ Async Request
• 클 라 이 언 트 에 이 벤 트 푸 시 , 긴 연 산
• 상 당 히 쉽 게 할 수 있 다 .
• 조 금 더 복 잡한 상 황에 대 해 서 는 구 현 이 어
려 움
Web Messaging Architecture
• WebSocket -> Low-level transport
• SockJS -> fallback options
• STOMP -> application-level protocol
STOMP Frame
>>> SEND
destination:/app/hello
content-length:19
{"name":"honeymon"}
stomp.js:130
<<< MESSAGE
destination:/topic/greetings
content-type:application/json;charset=UTF-8
subscription:sub-0
message-id:9n_v3m2s-0
content-length:30
{"content":"Hello, honeymon!"}
Handle Messages from WebSocket clients
@Controller
public class PortfolioController {
@MessageMapping("/greetings")
public void add(String payload) {
// …
}
}
Broadcast Messages to WebSocket Clients
@Autowired
private SimpMessagingTemplate messagingTemplate;
@RequestMapping(value = "/boardcast-echo", method = RequestMethod.POST)
public void broadcastEcho() {
this.messagingTemplate.convertAndSend("/app/stomp/echo", "Hello, KSUG");
}
Spring Framework 4.2
HTTP Streaming
• New return type ResponseBodyEmitter
• Write a series of Objects to response body
• via HttpMessageConverter
• Also works with ResponseEntity
HTTP Streaming Example
@RequestMapping
public ResponseBodyEmitter handle() {
ResponseBodyEmitter emitter = new ResponseBodyEmitter();
// …
return emitter;
}
// Later from some other thread
emitter.send(new Foo());
emitter.send(new Bar());
emitter.complete()
HTTP Streaming: SSE-style
• SseEmitter extends ResponseBodyEmitter
• ResponseBodyEmitter와 같은 동 작 을 하 지
만 다 른 점 하 나 !
– SSE-style: W3C Server-Send Event
specifications
Server-sent events example
@RequestMapping
public SseEmitter handle() {
SseEmitter emitter = new SseEmitter();
// ...
return emitter;
}
// Later from some other thread
emitter.send(event().name("foo").data(new Foo()));
emitter.send(event().name("bar").data(new Bar()));
emitter.complete();
HTTP Streaming: Directly to Response
@RequestMapping
public StreamingResponseBody handle() {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream out) {
// ...
}
}
}
HTTP caching update
• CacheControl builder
• Configurable in various places
– WebContentGenerator/Interceptor
– ResourceHttpRequestHandler
– ResponseEntity
• Improved ETag/Last-Modified support in
WebRequest
CORS support
• 계 층 적 인 접 근
• 세 밀 한 설 정
– @CrossOrigin 컨 트 롤 러 에 사 용
• URL 패 턴 을 기 반 으 로 한 전 역 설 정
How CORS is supported
• AbstractHandlerMapping 에 의 해 생 성
• 하 위 클 래 스 에 대 한 CORS 메 타 데 이 터 제 공
– @CrossOrigin
– CorsConfigurationSource
• AbstractHandlerMapping 안 에
CorsProcessor 설 정
– CORS 체 크 수 행 , 응 답 헤 더 설 정
@RequestMapping meta annotation
@RequestMapping(method = RequestMethod.POST, produces =
MediaType.APPLICATION_JSON_VALUE, consumes =
MediaType.APPLICATION_JSON_VALUE)
public @interface PostJson {
String value() default "";
}
//..
@PostJson("/account")
public ResponseEntity<Account> add(Account account) {
return ResponseEntity.ok(account);
}
Javascript View Templating
• Server and Client-side rendering
– using same template engine(e.g. React)
• `ScriptTemplateView`, `ViewResolver`
– built on Nashorn(JDK 1.8)
• 서 버 에 서 초 기 화해 두 고 , 서 버 에 서 가 져 온
코 드 를 가 지 고 클 라 이 언 트 사 이 드 에 서 랜
더 링
다 음 세 션 !! + 정 성 용 Isomorphic!!
MISC == 기 타 등 등
• 정 적 자 원 에 대 한 byte-range 요 청 지 원
• @ExceptionHandler 메 서 드 에 메 서 드 인 자
로 HandlerMethod 사 용
• MvcUriComponentsBuilder custom baseUri
STOMP/WebSocket
• @ControllerAdvice 기 반 으 로 메 서 드 전 역 에
@Exceptionhandler 적 용 가 능
• @SendTo/SendToUser Destination value
placehodler 정 의 : @DestinationVariable
• 다 중 앱 서 버 사 이 에 서 사 용 자 목 적 지 사 용
• SockJS 내 에 서 CORS 향상
Simple Broker(STOMP over WebSocket)
• HeartBeat support
• SpEL-based message selector
SUBSCRIBE
destination:/app/greetings
selector:headers.foo == ‘bar’
STOMP client
• 자 바 를 사 용 하 여 WebSocket 혹 은 TCP 접 근
• 테 스 트 에 유 용 함
• 서 버 사 이 드 에 서 STOMP broker 접 근
정 리
• 설 정 의 응 집 도 를 높 이 고 !
• 세 부 설 정 은 진 입 지 점 에 서 도 가 능 !
• 웹 소 켓 의 기 능 을 HTTP에 서 도 !
• 조 금 더 ! 빠르 게 ! 쉽 게 !
?WHY
발 표 자 료
• 예 제 :
– https://github.com/ihoneymon/rocking-the-
spring-4x-web-application
참 조 자 료
• Spring Framework - wikipedia
• 4.0.0 release
• Spring 4 Web applications
• Spring Framework 4.0 Web Applications - SpringOne 2014
• Overview of Spring 4.0 - 박 용 권 , KSUG
• Spring MVC 4.2: New and Noteworthy
• Workshop - From Spring 4.0 To 4.2
• Exception handling in Spring MVC
• Spring - Modify response headers after controller processing
• Using WebSocket to build an interactive web application
• CORS support in Spring Framework
• Isomorphic templating with Spring Boot, Nashorn and React
• Script template
• HTTP Streaming
KSUG 일 꾼 단 모 집 !
끝 !!
궁 금 하 신 것 이 있 으 시 다 면 ,
ihoneymon@gmail.com
@ihoneymon

Spring 4.x Web Application 살펴보기

  • 1.
    Spring 4.x Web ApplicationOverview 최 신 웹 트 렌 드 를 따 르 는 스 프 링 더 듬 기
  • 2.
    발 표 자소 개 •이 름 : 김 지 헌 (== honeymon) ­ ihoneymon@gmail.com ­ http://honeymon.io ­ 이 노 트 리 (http://innotree.com) 근 무 ­ KSUG 일 꾼 단 소 속 잡무 수 행 ­ 개 발 자 … ­ 종 합레 저 스 포 츠 인 을 표 방
  • 3.
    Spring framework ● 2003,JDK 1.4 ● https://spring.io/blog/2004/03 /24/spring-framework-1-0- final-released ● Annotation, REST, SPAs, WebSocket 가 요 구 되 기 전
  • 4.
    Programming Model Version @Controller2.5(2007) REST 3.0(2009) Async HTTP 3.2(2012) WebSocket 4.0(2013) Programming Model
  • 5.
    스 프 링프 레 임 워 크 의 성 공 포 인 트
  • 6.
    간결 하 고, 깔 끔 하 고 , 안 정 적 인 설 계
  • 7.
  • 8.
    HTTP, REST, Messaging 등다 양 한 지 원
  • 9.
    강력 한 커뮤 니 티 !!
  • 10.
  • 11.
    변 화하 는환경 에 따 라 끊 임 없 이 진 화!
  • 12.
  • 13.
    @Controller method • @InitBinder •@ModelAttribute • @RequestMapping • @ExceptionHandler
  • 14.
    @RestController @Controller public class MyController{ @RequestMapping @ResponseBody public Foo handleFoo() { } @RequestMapping @ResponseBody public Boo handleBoo() { } } @RestController public class MyController { @RequestMapping public Foo handleFoo() { } @RequestMapping public Boo handleBoo() { } } @RestController = @Controller + @ResponseBody
  • 15.
  • 16.
    @ControllerAdvice • @ControllerAdvice • @ControllerAdvice(annotations=RestController.class) •@ControllerAdvice(basePackages="org.ksug") • @ControllerAdvice(assignableTypes= {MyController.class})
  • 17.
    ResponseEntityExceptionHandler - v3.2 •@ControllerAdvice를 함께 사 용 하 는 예 외 처 리 추 상 클 래 스 • Spring MVC 예 외 처 리 • REST API 친 화적 임
  • 18.
    ResponseBodyAdvice • @ControllerAdvice와 함께사 용 하 는 인 터 페 이 스 • v4.1에 추 가 됨 • 컨 트 롤 러 에 서 반 환된 응 답 결 과를 HttpMessageConverter가 다 루 기 전 에 작 업 RequestBodyAdvice + v4.2
  • 19.
    Jackson 이 야기 • Jackson: JSON & XML 조 작 • Jackson2ObjectMapperBuilder 를 이 용 해 서 ObjectMapper 인 스 턴 스 를 생 성 • LastestJackon integration improvements in spring – @JsonView: Jackson's Serialization View – JSONP: @ResponseEntity & ResponseEntity
  • 20.
    @RequestMapping • java.util.Optional(JDK 8)지 원 • ResponseEntity/RequestEntity buider-style method • MvcUriComponentBuilder를 사 용 하 여 다 른 컨 트 롤 러 의 메 서 드 를 호 출 할 수 있 는 URI 생 성 • @ModelAttribute 사 이 의 의 존 성 부 여
  • 21.
    정 적 자원 지 원 • ResourceHttpRequesthandler < 4.1 • ResourceResolver, ResourceTransformer, ResourceUrlProvider 4.1+ • 컨 텐 츠 기 반 해 시 를 가 진 Versioned URL – e.g. "/css/font-awesome.min-7fbe76cdac.css" • 보 다 자 세 한 사 항은 !! – Resource Handling Spring MVC 4.1 - SpringOne 2014 – Resource handling Spring MVC - Adieu 2014, 봄 싹(박 용 권 )
  • 22.
    Groovy markup template •HTML 템 플 릿 용 DSL을 Groovy 로 컴 파일 • Groovy 의 강력 한 힘 으 로 ! • See GroovyMarkup View Javascript Templating + v4.2
  • 23.
    MVC 설 정 •ViewResolver 등 록 지 원 • ViewController 설 정 • Path matching 설 정
  • 24.
    비 동 기HTTP 요 청 • Servlet 3.0+ Async Request • 클 라 이 언 트 에 이 벤 트 푸 시 , 긴 연 산 • 상 당 히 쉽 게 할 수 있 다 . • 조 금 더 복 잡한 상 황에 대 해 서 는 구 현 이 어 려 움
  • 25.
    Web Messaging Architecture •WebSocket -> Low-level transport • SockJS -> fallback options • STOMP -> application-level protocol
  • 26.
    STOMP Frame >>> SEND destination:/app/hello content-length:19 {"name":"honeymon"} stomp.js:130 <<<MESSAGE destination:/topic/greetings content-type:application/json;charset=UTF-8 subscription:sub-0 message-id:9n_v3m2s-0 content-length:30 {"content":"Hello, honeymon!"}
  • 27.
    Handle Messages fromWebSocket clients @Controller public class PortfolioController { @MessageMapping("/greetings") public void add(String payload) { // … } }
  • 28.
    Broadcast Messages toWebSocket Clients @Autowired private SimpMessagingTemplate messagingTemplate; @RequestMapping(value = "/boardcast-echo", method = RequestMethod.POST) public void broadcastEcho() { this.messagingTemplate.convertAndSend("/app/stomp/echo", "Hello, KSUG"); }
  • 29.
  • 30.
    HTTP Streaming • Newreturn type ResponseBodyEmitter • Write a series of Objects to response body • via HttpMessageConverter • Also works with ResponseEntity
  • 31.
    HTTP Streaming Example @RequestMapping publicResponseBodyEmitter handle() { ResponseBodyEmitter emitter = new ResponseBodyEmitter(); // … return emitter; } // Later from some other thread emitter.send(new Foo()); emitter.send(new Bar()); emitter.complete()
  • 32.
    HTTP Streaming: SSE-style •SseEmitter extends ResponseBodyEmitter • ResponseBodyEmitter와 같은 동 작 을 하 지 만 다 른 점 하 나 ! – SSE-style: W3C Server-Send Event specifications
  • 33.
    Server-sent events example @RequestMapping publicSseEmitter handle() { SseEmitter emitter = new SseEmitter(); // ... return emitter; } // Later from some other thread emitter.send(event().name("foo").data(new Foo())); emitter.send(event().name("bar").data(new Bar())); emitter.complete();
  • 34.
    HTTP Streaming: Directlyto Response @RequestMapping public StreamingResponseBody handle() { return new StreamingResponseBody() { @Override public void writeTo(OutputStream out) { // ... } } }
  • 35.
    HTTP caching update •CacheControl builder • Configurable in various places – WebContentGenerator/Interceptor – ResourceHttpRequestHandler – ResponseEntity • Improved ETag/Last-Modified support in WebRequest
  • 36.
    CORS support • 계층 적 인 접 근 • 세 밀 한 설 정 – @CrossOrigin 컨 트 롤 러 에 사 용 • URL 패 턴 을 기 반 으 로 한 전 역 설 정
  • 37.
    How CORS issupported • AbstractHandlerMapping 에 의 해 생 성 • 하 위 클 래 스 에 대 한 CORS 메 타 데 이 터 제 공 – @CrossOrigin – CorsConfigurationSource • AbstractHandlerMapping 안 에 CorsProcessor 설 정 – CORS 체 크 수 행 , 응 답 헤 더 설 정
  • 38.
    @RequestMapping meta annotation @RequestMapping(method= RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public @interface PostJson { String value() default ""; } //.. @PostJson("/account") public ResponseEntity<Account> add(Account account) { return ResponseEntity.ok(account); }
  • 39.
    Javascript View Templating •Server and Client-side rendering – using same template engine(e.g. React) • `ScriptTemplateView`, `ViewResolver` – built on Nashorn(JDK 1.8) • 서 버 에 서 초 기 화해 두 고 , 서 버 에 서 가 져 온 코 드 를 가 지 고 클 라 이 언 트 사 이 드 에 서 랜 더 링 다 음 세 션 !! + 정 성 용 Isomorphic!!
  • 40.
    MISC == 기타 등 등 • 정 적 자 원 에 대 한 byte-range 요 청 지 원 • @ExceptionHandler 메 서 드 에 메 서 드 인 자 로 HandlerMethod 사 용 • MvcUriComponentsBuilder custom baseUri
  • 41.
    STOMP/WebSocket • @ControllerAdvice 기반 으 로 메 서 드 전 역 에 @Exceptionhandler 적 용 가 능 • @SendTo/SendToUser Destination value placehodler 정 의 : @DestinationVariable • 다 중 앱 서 버 사 이 에 서 사 용 자 목 적 지 사 용 • SockJS 내 에 서 CORS 향상
  • 42.
    Simple Broker(STOMP overWebSocket) • HeartBeat support • SpEL-based message selector SUBSCRIBE destination:/app/greetings selector:headers.foo == ‘bar’
  • 43.
    STOMP client • 자바 를 사 용 하 여 WebSocket 혹 은 TCP 접 근 • 테 스 트 에 유 용 함 • 서 버 사 이 드 에 서 STOMP broker 접 근
  • 44.
    정 리 • 설정 의 응 집 도 를 높 이 고 ! • 세 부 설 정 은 진 입 지 점 에 서 도 가 능 ! • 웹 소 켓 의 기 능 을 HTTP에 서 도 ! • 조 금 더 ! 빠르 게 ! 쉽 게 !
  • 45.
  • 46.
    발 표 자료 • 예 제 : – https://github.com/ihoneymon/rocking-the- spring-4x-web-application
  • 47.
    참 조 자료 • Spring Framework - wikipedia • 4.0.0 release • Spring 4 Web applications • Spring Framework 4.0 Web Applications - SpringOne 2014 • Overview of Spring 4.0 - 박 용 권 , KSUG • Spring MVC 4.2: New and Noteworthy • Workshop - From Spring 4.0 To 4.2 • Exception handling in Spring MVC • Spring - Modify response headers after controller processing • Using WebSocket to build an interactive web application • CORS support in Spring Framework • Isomorphic templating with Spring Boot, Nashorn and React • Script template • HTTP Streaming
  • 48.
    KSUG 일 꾼단 모 집 !
  • 49.
  • 50.
    궁 금 하신 것 이 있 으 시 다 면 , ihoneymon@gmail.com @ihoneymon