SlideShare a Scribd company logo
Spring 4 Web Applications
Rossen Stoyanchev
Pivotal Inc
About the speaker
● Spring Framework committer
● Spring MVC
● Spring WebSocket and Messaging
Spring MVC
● Since 2003 (circa JDK 1.4)
● Before Java annotations, REST, SPAs, ...
● Continued success, evolution
● Most popular status today
Programming Model Evolution
● @Controller ………...………... 2.5 (2007)
● REST …………………………….. 3.0 (2009)
● Async requests ……………….. 3.2 (2012)
● WebSocket messaging …….. 4.0 (2013)
● Simple, clean design at the core
● Friendly to extension
● Embraces HTTP and REST
● Community requests
Keys to Success
Always Evolving
● One of most actively developed parts of
Spring Framework
● Continuous flow of ideas and requests from
the community
● Improvements, new features, even modules
with each new version
@MVC
@Controller
@InitBinder
@ModelAttribute
@RequestMapping
@ExceptionHandler
@RestController
@RestController
public class MyController {
@RequestMapping @ResponseBody
public Foo handle() { … }
@RequestMapping @ResponseBody
public Bar handle() { … }
}
Beyond Class Hierarchy
@ControllerAdvice
@InitBinder
@ModelAttribute
@ExceptionHandler
Selectors
@ControllerAdvice => “Apply to every @Controller”
@ControllerAdvice(basePackages = "org.app.module")
@ControllerAdvice(annotations = RestController.class)
@ControllerAdvice(assignableTypes =
{BaseController1.class, BaseController2.class})
ResponseEntityExceptionHandler
● Base class for use with @ControllerAdvice
● Handle Spring MVC exceptions
● REST API error details in response body
ResponseBodyAdvice
● Interface for use with @ControllerAdvice
● Customize response before @ResponseBody &
ResponseEntity are written
● Built-in usages
○ @JsonView on @RequestMapping methods
○ JSONP
Further Jackson Support
● Use Jackson for both JSON and XML
● ObjectMapper builder
● Highly recommended read:
https://spring.io/blog/2014/12/02/
latest-jackson-integration-
improvements-in-spring
@RequestMapping methods
● java.util.Optional (JDK 1.8) support
● ListenableFuture return value
● ResponseEntity/RequestEntity builders
● Links to @MVC methods
● @ModelAttribute method ordering
ResponseEntityBuilder
String body = "Hello";
HttpHeaders hdrs = new HttpHeaders()
headers.setLocation(location);
new ResponseEntity<String>(body, hdrs, CREATED);
vs
ResponseEntity.created(location).body("Hello");
RequestEntityBuilder
HttpHeaders headers = new HttpHeaders();
headers.setAccept(MediaType.APPLICATION_JSON);
new HttpEntity("Hello", headers);
vs
RequestEntity.post(uri)
.accept(MediaType.APPLICATION_JSON)
.body("Hello");
Link to @RequestMapping
● Simulate controller method invocation
fromMethodCall(on(MyController.class).getAddress("US"))
.buildAndExpand(1).toUri();
● Uses proxy, similar to testing w/ mocks
● See section on Building URIs
How to link from views?
● Refer to @RequestMapping by name
● Default name assigned to every mapping
○ or use @RequestMapping(name=”..”)
● See subsection in Building URIs
@ModelAttribute Ordering
<- Call this 1st
@ModelAttribute("foo")
public Object getFoo() {
}
@ModelAttribute("bar")
public Object getBar(@ModelAttribute("foo") Object foo) {
}
Uses “foo”
Creates “foo”
Static Resources
● Key topic for web applications today
○ Optimize .. minify, concatenate
○ Transform .. sass, less
○ HTTP caching .. versioned URLs
○ CDN
○ Prod vs dev
Static Resources in 4.1
● Build on existing
ResourceHttpRequestHandler
● Add abstractions to resolve and transform
resources in a chain
● Prepare “public” resource URL
URL “Fingerprinting”
● HTTP “cache busting”
● Version URL with content-based hash
● Add aggressive cache headers (e.g. +1 year)
Example URL:
“/css/font-awesome.min-7fbe76cdac.css”
Static Resources Continued
See Resource Handling talk on Youtube,
browse the slides,
or check the source code.
Groovy Markup Templating
● DRY markup based on Groovy 2.3
● Like HAML in Ruby on Rails
yieldUnescaped '<!DOCTYPE html>'
html(lang:'en') {
head {
title('My page')
}
body {
p('This is an example of HTML contents')
}
}
MVC Config
● We now have ViewResolver registry
● ViewController can do more
○ redirects, 404s, etc.
● Patch matching by popular demand
○ suffix patterns, trailing slashes, etc.
Servlet 3 Async Requests
● Since v3.2
○ Long polling, HTTP streaming
● Server can push events to client
○ chat, tweet stream
● Relatively simple, close to what we know
● Not easy for more advanced uses
○ games, finance, collaboration
Web Messaging
● WebSocket protocol
○ bi-directional messaging between client & server
● SockJS fallback
○ WebSocket emulation (IE < 10, proxy issues, etc.)
● STOMP
○ Simple messaging sub-protocol
○ Like HTTP over TCP
Why not just WebSocket?
● Too low level
● Practically a TCP socket
● Just like HTTP enables RESTful
architecture, STOMP enables messaging
● In the absence of a protocol, a custom
protocol will have to be used
Example STOMP Frame
SEND
destination:/app/greetings
content-type:text/plain
Hello world!
Handle a Message
@Controller
public class PortfolioController {
@MessageMapping("/greetings")
public void add(String payload) { … }
}
Messaging + REST
@Controller
public class PortfolioController {
@MessageMapping("/greetings")
public void add(String payload) { … }
@RequestMapping("/greetings", method=GET)
public String get() { … }
}
SockJS
● Exact same WebSocket API
● Different transports underneath
○ long polling, HTTP streaming
● Wide range of browsers and versions
● WebSocket alone not practically usable
without fallback options today
WebSocket Continued
See presentation:
https://github.com/rstoyanchev/
springx2013-websocket
There is also a video available.
Spring Boot
● You are an expert but how long would it take
you to start a new web application?
● Lot of choices to be made
● Boot makes reasonable default choices
● So you can be up and running in minutes
Spring Boot Web App
@RestController
@EnableAutoConfiguration
public class Example {
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
@RequestMapping("/")
public String home() {
return "Hello World!";
}
}
REST API Docs
● Good REST API documentation can not be
fully generated
● Every good API guide has some stories and
use cases with example usage
● Yet manually writing it all is too much
Spring REST Docs
● What if you could write real tests that
demonstrate your REST API?
● Using Spring MVC Test...
● Then insert the code w/ actual output in your
Asciidoctor documentation
Spring REST Docs Continued
Check out this webinar by Andy Wilkinson
Server-Sent Events v4.2
@RequestMapping
public ResponseEntity<SseEmitter> handle() {
SseEmitter emitter = new SseEmitter();
// ...
return emitter;
}
// Later from another thread
emitter.send(event().name("foo").data(foo));
…
emitter.complete();
Server-Sent Events v4.2
@RequestMapping
public ResponseEntity<SseEmitter> handle() {
if ( … ) {
return ResponseEntity.status(204).body(null);
}
else {
// …
ResponseEntity.ok(sseEmitter);
}
}
SPR-12672
HTTP Caching v4.2
● Comprehensive update according to the
most recent HTTP 1.1. spec updates
● Central and per-request support for all
Cache-Control directives
● A deep eTag strategy
SPR-11792
CORS v4.2
● Built-in support within Spring MVC
● Both central and fine-grained
● @CrossOrigin
● CorsConfigurationSource
SPR-9278
Custom @RequestMapping v4.2
@RequestMapping(
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE
consumes = MediaType.APPLICATION_JSON_VALUE)
public @interface PostJson {
String value() default "";
}
@PostJson("/input")
public Output myMethod(Input input) {
}
SPR-12296
JavaScript Templating v4.2
● Server-side JavaScript templates
● See very long SPR-12266
● Current plan is to plug Nashorn (JDK 1.8)
behind the ViewResolver/View contracts
● Much like we did for Groovy in 4.1
STOMP Client v4.2
● There aren’t any good Java clients
● So we’ve decided to write one
● Good for testing at least
● Like we added SockJS Java client in 4.1
SPR-11588
Topical Guides
● Part of effort to overhaul Spring Framework
reference documentation
● Separate “conceptual” information from
pure reference
● Example guides
○ “What is Spring”, “Intro to Spring Config”, etc.
● Track topical-guides repo
Questions
http://twitter.com/rstoya05
http://pivotal.io

More Related Content

What's hot

Spring MVC
Spring MVCSpring MVC
Spring MVC
yuvalb
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache Geode
VMware Tanzu
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC
Spring MVCSpring MVC
Spring MVC
Emprovise
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Aaron Schram
 
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Sam Brannen
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
dasguptahirak
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
Joshua Long
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Rajind Ruparathna
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 

What's hot (19)

Spring MVC
Spring MVCSpring MVC
Spring MVC
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache Geode
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 

Viewers also liked

Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
Jordan Silva
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
Ilio Catallo
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Dineesha Suraweera
 
Ajug - The Spring Update
Ajug - The Spring UpdateAjug - The Spring Update
Ajug - The Spring Update
Gunnar Hillert
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
David Gómez García
 
The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of ControlVisualBee.com
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite SlideDaniel Adenew
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
kensipe
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 

Viewers also liked (11)

Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Ajug - The Spring Update
Ajug - The Spring UpdateAjug - The Spring Update
Ajug - The Spring Update
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of Control
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
 

Similar to Spring 4 Web App

RESTEasy
RESTEasyRESTEasy
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
JBug Italy
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017
Matt Raible
 
Engage 2023: Taking Domino Apps to the next level by providing a Rest API
Engage 2023: Taking Domino Apps to the next level by providing a Rest APIEngage 2023: Taking Domino Apps to the next level by providing a Rest API
Engage 2023: Taking Domino Apps to the next level by providing a Rest API
Serdar Basegmez
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
Geoffrey Fox
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
Yahoo
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
5.node js
5.node js5.node js
5.node js
Geunhyung Kim
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
 
Understanding ASP.NET Under The Cover - Miguel A. Castro
Understanding ASP.NET Under The Cover - Miguel A. CastroUnderstanding ASP.NET Under The Cover - Miguel A. Castro
Understanding ASP.NET Under The Cover - Miguel A. CastroMohammad Tayseer
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applicationsdominion
 
Oredev 2009 JAX-RS
Oredev 2009 JAX-RSOredev 2009 JAX-RS
Oredev 2009 JAX-RS
Niklas Gustavsson
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
Paulo Victor Gomes
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
Andrei Sebastian Cîmpean
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservicelonegunman
 

Similar to Spring 4 Web App (20)

RESTEasy
RESTEasyRESTEasy
RESTEasy
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017
 
Engage 2023: Taking Domino Apps to the next level by providing a Rest API
Engage 2023: Taking Domino Apps to the next level by providing a Rest APIEngage 2023: Taking Domino Apps to the next level by providing a Rest API
Engage 2023: Taking Domino Apps to the next level by providing a Rest API
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
5.node js
5.node js5.node js
5.node js
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Understanding ASP.NET Under The Cover - Miguel A. Castro
Understanding ASP.NET Under The Cover - Miguel A. CastroUnderstanding ASP.NET Under The Cover - Miguel A. Castro
Understanding ASP.NET Under The Cover - Miguel A. Castro
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Oredev 2009 JAX-RS
Oredev 2009 JAX-RSOredev 2009 JAX-RS
Oredev 2009 JAX-RS
 
Ajax
AjaxAjax
Ajax
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
 

More from Rossen Stoyanchev

Reactive Web Applications
Reactive Web ApplicationsReactive Web Applications
Reactive Web Applications
Rossen Stoyanchev
 
Spring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and Noteworthy
Rossen Stoyanchev
 
Intro To Reactive Programming
Intro To Reactive ProgrammingIntro To Reactive Programming
Intro To Reactive Programming
Rossen Stoyanchev
 
Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1
Rossen Stoyanchev
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
Rossen Stoyanchev
 
Spring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutSpring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutRossen Stoyanchev
 

More from Rossen Stoyanchev (6)

Reactive Web Applications
Reactive Web ApplicationsReactive Web Applications
Reactive Web Applications
 
Spring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and Noteworthy
 
Intro To Reactive Programming
Intro To Reactive ProgrammingIntro To Reactive Programming
Intro To Reactive Programming
 
Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
 
Spring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutSpring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing About
 

Recently uploaded

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 

Spring 4 Web App

  • 1. Spring 4 Web Applications Rossen Stoyanchev Pivotal Inc
  • 2. About the speaker ● Spring Framework committer ● Spring MVC ● Spring WebSocket and Messaging
  • 3. Spring MVC ● Since 2003 (circa JDK 1.4) ● Before Java annotations, REST, SPAs, ... ● Continued success, evolution ● Most popular status today
  • 4. Programming Model Evolution ● @Controller ………...………... 2.5 (2007) ● REST …………………………….. 3.0 (2009) ● Async requests ……………….. 3.2 (2012) ● WebSocket messaging …….. 4.0 (2013)
  • 5. ● Simple, clean design at the core ● Friendly to extension ● Embraces HTTP and REST ● Community requests Keys to Success
  • 6. Always Evolving ● One of most actively developed parts of Spring Framework ● Continuous flow of ideas and requests from the community ● Improvements, new features, even modules with each new version
  • 8. @RestController @RestController public class MyController { @RequestMapping @ResponseBody public Foo handle() { … } @RequestMapping @ResponseBody public Bar handle() { … } }
  • 10. Selectors @ControllerAdvice => “Apply to every @Controller” @ControllerAdvice(basePackages = "org.app.module") @ControllerAdvice(annotations = RestController.class) @ControllerAdvice(assignableTypes = {BaseController1.class, BaseController2.class})
  • 11. ResponseEntityExceptionHandler ● Base class for use with @ControllerAdvice ● Handle Spring MVC exceptions ● REST API error details in response body
  • 12. ResponseBodyAdvice ● Interface for use with @ControllerAdvice ● Customize response before @ResponseBody & ResponseEntity are written ● Built-in usages ○ @JsonView on @RequestMapping methods ○ JSONP
  • 13. Further Jackson Support ● Use Jackson for both JSON and XML ● ObjectMapper builder ● Highly recommended read: https://spring.io/blog/2014/12/02/ latest-jackson-integration- improvements-in-spring
  • 14. @RequestMapping methods ● java.util.Optional (JDK 1.8) support ● ListenableFuture return value ● ResponseEntity/RequestEntity builders ● Links to @MVC methods ● @ModelAttribute method ordering
  • 15. ResponseEntityBuilder String body = "Hello"; HttpHeaders hdrs = new HttpHeaders() headers.setLocation(location); new ResponseEntity<String>(body, hdrs, CREATED); vs ResponseEntity.created(location).body("Hello");
  • 16. RequestEntityBuilder HttpHeaders headers = new HttpHeaders(); headers.setAccept(MediaType.APPLICATION_JSON); new HttpEntity("Hello", headers); vs RequestEntity.post(uri) .accept(MediaType.APPLICATION_JSON) .body("Hello");
  • 17. Link to @RequestMapping ● Simulate controller method invocation fromMethodCall(on(MyController.class).getAddress("US")) .buildAndExpand(1).toUri(); ● Uses proxy, similar to testing w/ mocks ● See section on Building URIs
  • 18. How to link from views? ● Refer to @RequestMapping by name ● Default name assigned to every mapping ○ or use @RequestMapping(name=”..”) ● See subsection in Building URIs
  • 19. @ModelAttribute Ordering <- Call this 1st @ModelAttribute("foo") public Object getFoo() { } @ModelAttribute("bar") public Object getBar(@ModelAttribute("foo") Object foo) { } Uses “foo” Creates “foo”
  • 20. Static Resources ● Key topic for web applications today ○ Optimize .. minify, concatenate ○ Transform .. sass, less ○ HTTP caching .. versioned URLs ○ CDN ○ Prod vs dev
  • 21. Static Resources in 4.1 ● Build on existing ResourceHttpRequestHandler ● Add abstractions to resolve and transform resources in a chain ● Prepare “public” resource URL
  • 22. URL “Fingerprinting” ● HTTP “cache busting” ● Version URL with content-based hash ● Add aggressive cache headers (e.g. +1 year) Example URL: “/css/font-awesome.min-7fbe76cdac.css”
  • 23. Static Resources Continued See Resource Handling talk on Youtube, browse the slides, or check the source code.
  • 24. Groovy Markup Templating ● DRY markup based on Groovy 2.3 ● Like HAML in Ruby on Rails yieldUnescaped '<!DOCTYPE html>' html(lang:'en') { head { title('My page') } body { p('This is an example of HTML contents') } }
  • 25. MVC Config ● We now have ViewResolver registry ● ViewController can do more ○ redirects, 404s, etc. ● Patch matching by popular demand ○ suffix patterns, trailing slashes, etc.
  • 26. Servlet 3 Async Requests ● Since v3.2 ○ Long polling, HTTP streaming ● Server can push events to client ○ chat, tweet stream ● Relatively simple, close to what we know ● Not easy for more advanced uses ○ games, finance, collaboration
  • 27. Web Messaging ● WebSocket protocol ○ bi-directional messaging between client & server ● SockJS fallback ○ WebSocket emulation (IE < 10, proxy issues, etc.) ● STOMP ○ Simple messaging sub-protocol ○ Like HTTP over TCP
  • 28. Why not just WebSocket? ● Too low level ● Practically a TCP socket ● Just like HTTP enables RESTful architecture, STOMP enables messaging ● In the absence of a protocol, a custom protocol will have to be used
  • 30. Handle a Message @Controller public class PortfolioController { @MessageMapping("/greetings") public void add(String payload) { … } }
  • 31. Messaging + REST @Controller public class PortfolioController { @MessageMapping("/greetings") public void add(String payload) { … } @RequestMapping("/greetings", method=GET) public String get() { … } }
  • 32. SockJS ● Exact same WebSocket API ● Different transports underneath ○ long polling, HTTP streaming ● Wide range of browsers and versions ● WebSocket alone not practically usable without fallback options today
  • 34. Spring Boot ● You are an expert but how long would it take you to start a new web application? ● Lot of choices to be made ● Boot makes reasonable default choices ● So you can be up and running in minutes
  • 35. Spring Boot Web App @RestController @EnableAutoConfiguration public class Example { public static void main(String[] args) { SpringApplication.run(Example.class, args); } @RequestMapping("/") public String home() { return "Hello World!"; } }
  • 36. REST API Docs ● Good REST API documentation can not be fully generated ● Every good API guide has some stories and use cases with example usage ● Yet manually writing it all is too much
  • 37. Spring REST Docs ● What if you could write real tests that demonstrate your REST API? ● Using Spring MVC Test... ● Then insert the code w/ actual output in your Asciidoctor documentation
  • 38. Spring REST Docs Continued Check out this webinar by Andy Wilkinson
  • 39. Server-Sent Events v4.2 @RequestMapping public ResponseEntity<SseEmitter> handle() { SseEmitter emitter = new SseEmitter(); // ... return emitter; } // Later from another thread emitter.send(event().name("foo").data(foo)); … emitter.complete();
  • 40. Server-Sent Events v4.2 @RequestMapping public ResponseEntity<SseEmitter> handle() { if ( … ) { return ResponseEntity.status(204).body(null); } else { // … ResponseEntity.ok(sseEmitter); } } SPR-12672
  • 41. HTTP Caching v4.2 ● Comprehensive update according to the most recent HTTP 1.1. spec updates ● Central and per-request support for all Cache-Control directives ● A deep eTag strategy SPR-11792
  • 42. CORS v4.2 ● Built-in support within Spring MVC ● Both central and fine-grained ● @CrossOrigin ● CorsConfigurationSource SPR-9278
  • 43. Custom @RequestMapping v4.2 @RequestMapping( method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE consumes = MediaType.APPLICATION_JSON_VALUE) public @interface PostJson { String value() default ""; } @PostJson("/input") public Output myMethod(Input input) { } SPR-12296
  • 44. JavaScript Templating v4.2 ● Server-side JavaScript templates ● See very long SPR-12266 ● Current plan is to plug Nashorn (JDK 1.8) behind the ViewResolver/View contracts ● Much like we did for Groovy in 4.1
  • 45. STOMP Client v4.2 ● There aren’t any good Java clients ● So we’ve decided to write one ● Good for testing at least ● Like we added SockJS Java client in 4.1 SPR-11588
  • 46. Topical Guides ● Part of effort to overhaul Spring Framework reference documentation ● Separate “conceptual” information from pure reference ● Example guides ○ “What is Spring”, “Intro to Spring Config”, etc. ● Track topical-guides repo