The Web and Spring MVC continue to be one of the most active areas of the
Spring Framework with each new release adding plenty of features and refinements
requested by the community. Furthermore version 4 added a significant choice
for web applications to build WebSocket-style architectures.
This talk provides an overview of the areas in which the framework has evolved
along with highlights of specific noteworthy features from the most recent
releases.
1 of 47
Downloaded 284 times
More Related Content
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
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
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”
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
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();
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
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