spring boot in the web tier - dave syer
TRANSCRIPT
Spring Boot for the Web TierDave Syer, 2015
AuthorDave Syer twitter: [@david_syer](http://twitter.com/david_syer) email: [email protected]
With thanks to: Stephane Nicoll (@snicoll) and Brian Clozel (@bclozel)
Presentation OverviewPart 1 Static Content
Part 2 Dynamic Content
Part 3 Embedded Server
Part 4 Other Stacks
SamplesSpring Boot @ConfigurationProperties Difference Analyser
https://github.com/dsyer/springboot4tw
1. Traditional server side rendering
2. Assets in separate project
3. Single project, webjars
4. Single project, build time assembly
5. Separate service and CORS
Static Content Serving FilesCan’t use /src/main/webapp for jar deployments
Put static files from src/main/resources/static
or …/public or …/resources or …/META-INF/resourcesImported "webjars" are automatically mapped
Static Content: NPM ToolchainFor serious front end developers the best choice is a Javascript toolchain.
Good community, lots of tools
Package static assets into a jar
And/or build them as part of a very thin back end
Spring Boot CLI makes a great lightweight back end in production or for Java devs
Static Content webjarsGreat for Java developers
No compilation or preprocessing
Huge range of Java Script and CSS libraries
Spring MVC support for webjarslocator
Static Content wro4jGreat for Java developers
Minification, consolidation, compilation, etc.
Often good enough
Tutorial (with AngularJS): https://spring.io/guides/tutorials/springsecurityandangularjs/
Dynamic Content API BackendJSON is trivial using Spring REST content negotiation
Add HttpMessageConverter beans and Spring Boot will try to do the right thingIt tries to be intelligent about the order
Add a HttpMessageConverters bean if you need more controlSpring Data REST is very popular for CRUD + query
Dynamic Content API DocumentationSpring Restdocs: http://spring.io/projects/springrestdocs
Generate documentation driven by test cases
Use (e.g.) asciidoctor to format and package it
Dynamic Content Templating SupportThymeleaf
Mustache
Groovy Template Language
Freemarker
Velocity (deprecated in Spring 4.3)
JSP (not recommended)
Hot ReloadIDEs support reloading static resources
Also small changes to Java classes
No agent: Spring Boot devtools
Agent: springloaded (Grails, JHipster), JRebel
Live reload (browser plugin)
Embedded ServerWhen using WARs a ServletContainerInitializer creates the Spring ApplicationContext
When running embedded the ApplicationContext creates the Server
Expects a single EmbeddedServletContainerFactory bean
Odd dance for WebApplicationContext.getServletContext() and ServletConfigAware
Embedded Server InitializationThe following beans are used to configure the server:
Servlet
Filter
ServletRequestListener
ServletRequestAttributeListener
HttpSessionAttributeListener
HttpSessionListener
ServletContextListener
Embedded Server InitializationFor more control use
ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean
@Beanpublic ServletRegistrationBean myServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(), "/mine"); bean.setAsyncSupported(false); bean.setInitParameters(Collections.singletonMap("debug", "true")); return bean;}
@Beanpublic FilterRegistrationBean myFilter() { return new FilterRegistrationBean(new MyFilter(), myServlet());}
Embedded Server InitializationBy design the following are not called with embedded servers:
javax.servlet.ServletContainerInitializer
org.springframework.web.WebApplicationInitializer
Use o.s.boot.context.embedded.ServletContextInitializer
/** * Configure the given {@link ServletContext} with any servlets, filters, listeners * context-params and attributes necessary for initialization. * @param servletContext the {@code ServletContext} to initialize * @throws ServletException if any call against the given {@code ServletContext} * throws a {@code ServletException} */ void onStartup(ServletContext servletContext) throws ServletException;
Embedded Server CustomizationUse ServerProperties (e.g. server.port=8080)
EmbeddedServletContainerCustomizer
Customize common things (e.g. the port, error-pages, context-path)Tomcat Specific
TomcatConnectorCustomizer
TomcatContextCustomizerJetty Specific
JettyServerCustomizerUndertow Specific
UndertowBuilderCustomizer
Embedded Server Tomcat Behind ProxyRunning behind nginx or Apache HTTPD is a common option
Especially useful with SSL termination
Real IP and SSL information is passed in headers
server.tomcat.protocol-header=x-forwarded-protoserver.tomcat.remote-ip-header=x-forwarded-for
Spring Boot 1.3.0 supports other containers in a similar way
Other StacksJAXRS: Jersey 1.x, Jersey 2.x, CXF (allegedly works)
Netty and NIO: Ratpack dsyer/springbootratpack
Servlet 2.5 scratches/springbootlegacy
Vaadin peholmst/vaadin4spring
RatpackOriginally inspired by Sinatra, but now pretty much diverged. Provides a nice programming model on top of Netty (taking advantage of nonblocking IOwhere possible).
2 approaches:
Ratpack embeds Spring (and uses it as a Registry), supported natively in RatpackSpring embeds Ratpack (and uses it as an HTTP listener) = springbootratpack
Spring Boot embedding RatpackTrivial example (single Handler):
@Beanpublic Handler handler() { return (context) -> { context.render("Hello World"); };}
Spring Boot embedding RatpackMore interesting example (Action<Chain> registers Handlers):
@Beanpublic Handler hello() { return (context) -> { context.render("Hello World"); };}
@Beanpublic Action<Chain> handlers() { return (chain) -> { chain.get(hello()); };}
Spring Boot Ratpack DSLA valid Ratpack Groovy application:
ratpack { handlers { get { render "Hello World" } }}
launched with Spring Boot:
$ spring run app.groovy
SamplesSpring Boot @ConfigurationProperties Difference Analyser
https://github.com/dsyer/springboot4tw
1. Traditional server side rendering: springboot4tw
2. Assets in separate project: springboot4twwebjs, springboot4twclient
3. Single project, webjars: springboot4twwebjars
4. Single project, build time assembly: springboot4twwro4j
5. Separate service and CORS: springboot4twversionsprovider
Questions?http://projects.spring.io/springboot/
http://projects.spring.io/springrestdocs/
https://github.com/dsyer/springboot4tw
https://github.com/SpringOne2GX2014/springbootforthewebtier
← →1 / 25Go to Slide: Go