Spring 4 Web App

R
Rossen StoyanchevSoftware Developer at Spring Framework team member, Pivotal senior staff
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
1 of 47

Recommended

Spring Framework - MVC by
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
10.7K views72 slides
Spring 4 on Java 8 by Juergen Hoeller by
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerZeroTurnaround
13.3K views19 slides
Next stop: Spring 4 by
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4Oleg Tsal-Tsalko
12K views38 slides
Spring 3.x - Spring MVC - Advanced topics by
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
14.4K views35 slides
Spring 4 final xtr_presentation by
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
869 views43 slides
Spring MVC Basics by
Spring MVC BasicsSpring MVC Basics
Spring MVC BasicsBozhidar Bozhanov
12.4K views14 slides

More Related Content

What's hot

Spring MVC by
Spring MVCSpring MVC
Spring MVCyuvalb
2.4K views47 slides
The Past Year in Spring for Apache Geode by
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeVMware Tanzu
230 views40 slides
Spring MVC 3.0 Framework by
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 FrameworkRavi Kant Soni (ravikantsoni03@gmail.com)
6.3K views24 slides
Spring MVC by
Spring MVCSpring MVC
Spring MVCEmprovise
2.4K views55 slides
Java Server Faces (JSF) - Basics by
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
12.3K views63 slides
Java servlet life cycle - methods ppt by
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
28.6K views101 slides

What's hot(19)

Spring MVC by yuvalb
Spring MVCSpring MVC
Spring MVC
yuvalb2.4K views
The Past Year in Spring for Apache Geode by VMware Tanzu
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache Geode
VMware Tanzu230 views
Spring MVC by Emprovise
Spring MVCSpring MVC
Spring MVC
Emprovise2.4K views
Java servlet life cycle - methods ppt by kamal kotecha
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha28.6K views
Spring Web MVC by zeeshanhanif
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif10.6K views
Spring Framework - Core by Dzmitry Naskou
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou34.8K views
Java Spring MVC Framework with AngularJS by Google and HTML5 by Tuna Tore
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 Tore4K views
Spring 4 advanced final_xtr_presentation by sourabh aggarwal
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
sourabh aggarwal650 views
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013 by Sam Brannen
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 Brannen11.4K views
Lecture 7 Web Services JAX-WS & JAX-RS by Fahad Golra
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra3.3K views
the Spring 4 update by Joshua Long
the Spring 4 updatethe Spring 4 update
the Spring 4 update
Joshua Long4.3K views
Lecture 3: Servlets - Session Management by Fahad Golra
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra2.8K views

Viewers also liked

Spring MVC Annotations by
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC AnnotationsJordan Silva
6.1K views16 slides
02 java spring-hibernate-experience-questions by
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
719 views7 slides
Spring 4 - A&BP CC by
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CCJWORKS powered by Ordina
774 views100 slides
Spring MVC - The Basics by
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The BasicsIlio Catallo
3.3K views148 slides
Introduction to Spring Framework by
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkDineesha Suraweera
1.7K views32 slides
Ajug - The Spring Update by
Ajug - The Spring UpdateAjug - The Spring Update
Ajug - The Spring UpdateGunnar Hillert
620 views51 slides

Viewers also liked(11)

Spring MVC Annotations by Jordan Silva
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
Jordan Silva6.1K views
02 java spring-hibernate-experience-questions by Dhiraj Champawat
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat719 views
Spring MVC - The Basics by Ilio Catallo
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
Ilio Catallo3.3K views
The Spring Framework: A brief introduction to Inversion of Control by VisualBee.com
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
VisualBee.com1.2K views
Spring mvc my Faviourite Slide by Daniel Adenew
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew1.7K views
Spring 3 Annotated Development by kensipe
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
kensipe3.7K views
Spring Web Service, Spring JMS, Eclipse & Maven tutorials by Raghavan Mohan
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan1.4K views

Similar to Spring 4 Web App

RESTEasy by
RESTEasyRESTEasy
RESTEasyMassimiliano Dessì
1.7K views37 slides
May 2010 - RestEasy by
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
1.3K views37 slides
Spring Web Services: SOAP vs. REST by
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
22.4K views42 slides
Front End Development for Back End Developers - UberConf 2017 by
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 2017Matt Raible
1.4K views109 slides
Engage 2023: Taking Domino Apps to the next level by providing a Rest API by
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 APISerdar Basegmez
3 views67 slides
Nodejs and WebSockets by
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
13.5K views35 slides

Similar to Spring 4 Web App(20)

May 2010 - RestEasy by JBug Italy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
JBug Italy1.3K views
Spring Web Services: SOAP vs. REST by Sam Brannen
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen22.4K views
Front End Development for Back End Developers - UberConf 2017 by Matt Raible
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 Raible1.4K views
Engage 2023: Taking Domino Apps to the next level by providing a Rest API by Serdar Basegmez
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 Basegmez3 views
Nodejs and WebSockets by Gonzalo Ayuso
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso13.5K views
05 status-codes by snopteck
05 status-codes05 status-codes
05 status-codes
snopteck255 views
CTS Conference Web 2.0 Tutorial Part 2 by Geoffrey Fox
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
Geoffrey Fox5.9K views
Mail OnLine Android Application at DroidCon - Turin - Italy by Yahoo
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
Yahoo1.2K views
Speed up your Web applications with HTML5 WebSockets by Yakov Fain
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain3.2K views
Understanding ASP.NET Under The Cover - Miguel A. Castro by Mohammad Tayseer
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
Mohammad Tayseer8.4K views
Using Ajax In Domino Web Applications by dominion
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
dominion1.6K views
Module design pattern i.e. express js by Ahmed Assaf
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf861 views
Building+restful+webservice by lonegunman
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
lonegunman357 views

More from Rossen Stoyanchev

Reactive Web Applications by
Reactive Web ApplicationsReactive Web Applications
Reactive Web ApplicationsRossen Stoyanchev
9K views52 slides
Spring MVC 4.2: New and Noteworthy by
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthyRossen Stoyanchev
4.5K views64 slides
Intro To Reactive Programming by
Intro To Reactive ProgrammingIntro To Reactive Programming
Intro To Reactive ProgrammingRossen Stoyanchev
1.3K views81 slides
Resource Handling in Spring MVC 4.1 by
Resource Handling in Spring MVC 4.1Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1Rossen Stoyanchev
14.1K views45 slides
Testing Web Apps with Spring Framework 3.2 by
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Rossen Stoyanchev
8K views51 slides
Spring 3.1 Features Worth Knowing About by
Spring 3.1 Features Worth Knowing AboutSpring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutRossen Stoyanchev
1.4K views24 slides

More from Rossen Stoyanchev(6)

Recently uploaded

DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft... by
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...Deltares
7 views18 slides
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptxNeo4j
8 views26 slides
SUGCON ANZ Presentation V2.1 Final.pptx by
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptxJack Spektor
23 views34 slides
nintendo_64.pptx by
nintendo_64.pptxnintendo_64.pptx
nintendo_64.pptxpaiga02016
5 views7 slides
360 graden fabriek by
360 graden fabriek360 graden fabriek
360 graden fabriekinfo33492
122 views25 slides
Agile 101 by
Agile 101Agile 101
Agile 101John Valentino
9 views20 slides

Recently uploaded(20)

DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft... by Deltares
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
Deltares7 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j8 views
SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor23 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492122 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares14 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi212 views
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik7 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor8 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana10 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views
Myths and Facts About Hospice Care: Busting Common Misconceptions by Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8712 views

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