SlideShare a Scribd company logo
Building Next-Gen Web Applications with the
   Spring 3.0 Web Stack
   Jeremy Grelle (@jeremyg484)
   Senior Member Technical Staff   (a.k.a, Open Source Web Dude)
   SpringSource a division of VMware




                                                               © 2010 SpringSource, A division of VMware. All rights reserved

Friday, July 23, 2010
Battling the rising complexity of web
                        application development by building on a
                        lightweight Spring foundation.




                                                                   2

Friday, July 23, 2010
Next-Gen? - The Modern Web Dilemma

    Web application requirement complexity continues to rise

      • How do we manage this complexity?

      • How do we expose our services to the largest possible audience?

      • How do we give users the best possible experience in the shortest amount of
         time?




                                                                                      3

Friday, July 23, 2010
The Spring Web Stack - Simplicity and Power

    The Spring Web Stack gives you:

      • unified programming model

      • multiple client types served with the same foundation

      • adaptability - the right approach (i.e., stateless, stateful) for the given use case




                                                                                               4

Friday, July 23, 2010
The Spring Web Stack

                                                       Spring
                          Spring Faces
                                                 BlazeDS Integration

                         Spring            Spring
                                                       Spring Security
                        Web Flow         JavaScript


                             Spring Framework and Spring MVC




                                                                         5

Friday, July 23, 2010
Web Stack Components

    Spring Framework and Spring MVC
      • The foundation for all other components

    Spring JavaScript
      • Ajax integration

    Spring Web Flow
      • Framework for stateful web conversation




                                                  6

Friday, July 23, 2010
Web Stack Components (cont.)

    Spring Security
      • Security framework

    Spring Faces
      • Integration with JavaServer Faces via Web Flow

    Spring BlazeDS Integration
      • Integration with Adobe Flex clients




                                                         7

Friday, July 23, 2010
Next-Gen? - Productivity: More Important than Ever Before

    Must resolve first obstacle to Java in the cloud

    Expectations are higher than ever before
    Success of Ruby on Rails et al has raised the bar for building simpler
      applications
    Developer choice crucial in determining cloud
      • Cloud apps often new
      • Often start simple
    Java/JVM technologies perceived as complex




                                      CONFIDENTIAL
                                                                              8

Friday, July 23, 2010
Increasing Productivity: The Opinionation Pyramid



      Opinionated, Productive


                                                 Ideal is to build on top of
                                                    powerful, extensible layers
                          Grails/
                           Roo

                                                 No need to move to
                           Spring                   introduce new runtime

                        Servlet/other
                        specifications           Never hit a wall
                            JVM


       Choice, Power

                                         CONFIDENTIAL
                                                                                  9

Friday, July 23, 2010
Grails

    The most popular rapid development framework for the JVM
    Solutions built on solid foundations




                                                      CONFIDENTIAL
                        SpringOne 2GX 2009. All rights reserved. Do not distribute without permission.   10

Friday, July 23, 2010
Spring Roo

    Higher Java productivity
    Familiar Java
      • Roo uses the Java APIs and standards you already
        know and trust.
    Usable and learnable
      • Roo features an extremely high level of usability and
        an advanced shell
    Trusted Spring Stack
      • Roo has no runtime – It’s just Spring
    Easy Roo removal
      • Roo can be easily removed from a user project in
        under five minutes.




                                           CONFIDENTIAL
                                                                11

Friday, July 23, 2010
Getting Started

    Create a new Spring MVC project from a template
      • Most use Roo to do this, either from an IDE like STS or the command-line

    Typical setup:

    One DispatcherServlet registered in web.xml
      • FrontController that dispatches web requests to your application logic
      • Generally the “default servlet” mapped to “/”
    Two Spring Containers (or ApplicationContexts) instantiated
      • 1 “root” context to host “shared resources” required by Servlets / Filters
      • 1 “web” context to host local application components delegated to by the
         DispatcherServlet
         • Your application components are typically discovered via classpath scanning




                                                                                         12

Friday, July 23, 2010
Demo




                        13

Friday, July 23, 2010
The Spring Web Stack

                                                     Spring
                        Spring Faces
                                               BlazeDS Integration

                    Spring               Spring
                                                     Spring Security
                   Web Flow            JavaScript


                           Spring Framework and Spring MVC




                                                                       14

Friday, July 23, 2010
Introduction to the MVC programming model

    DispatcherServlet requests are mapped to @Controller methods
      • @RequestMapping annotation used to define mapping rules
      • Method parameters used to obtain request input
      • Method return values used to generate responses
    Simplest possible @Controller:
    @Controller
    public class SimpleController {

    	      @RequestMapping("/simple")
    	      public @ResponseBody String simple() {
    	      	 return "Hello world!";
    	      }

    }

                                                                    15

Friday, July 23, 2010
Mapping Requests

    By path
      • @RequestMapping(“path”)

    By HTTP method
      • @RequestMapping(“path”, method=RequestMethod.GET)
      • POST, PUT, DELETE, OPTIONS, and TRACE are are also supported

    By presence of query parameter
      • @RequestMapping(“path”, method=RequestMethod.GET, params=”foo”)
      • Negation also supported: params={ “foo”, “!bar” })

    By presence of request header
      • @RequestMapping(“path”, header=”content-type=text/*”)
      • Negation also supported


                                                                          16

Friday, July 23, 2010
Mapping Requests (2)

    Simplest possible @Controller revisited
@Controller
public class SimpleControllerRevisited {

	      @RequestMapping(value="/simple/revisited",
                       method=RequestMethod.GET,
                       headers="Accept=text/plain")
	      public @ResponseBody String simple() {
	      	 return "Hello world revisited!";
	      }

}




                                                      17

Friday, July 23, 2010
Request Mapping at the Class Level

    @RequestMapping can be used at the class level
      • Concise way to map all requests within a path to a @Controller


   @Controller
   @RequestMapping("/accounts/*")
   public class AccountsController {
   	
   	 @RequestMapping("active")
   	 public @ResponseBody List<Account> active() { ... }
   	
   	 @RequestMapping("inactive")
   	 public @ResponseBody List<Account> inactive() { ... }
   }




                                                                         18

Friday, July 23, 2010
Obtaining Request Data

    Obtain request data by declaring method arguments
      • A query parameter value
         • @RequestParam(“name”)
      • A group of query parameter values
         • A custom JavaBean with a getName()/setName() pair for each parameter
      • A path element value
         • @PathVariable(“var”)
      • A request header value
         • @RequestHeader(“name”)
      • A cookie value
         • @CookieValue(“name”)
      • The request body
         • @RequestBody
      • The request body and any request header
         • HttpEntity<T>


                                                                                  19

Friday, July 23, 2010
Injecting Standard Objects

    A number of “standard arguments” can also be injected
       • Simply declare the argument you need as a method param

      HttpServletRequest (or its more portable WebRequest wrapper)
      Principal
      Locale
      InputStream
      Reader
      HttpServletResponse
      OutputStream
      Writer
      HttpSession



                                                                      20

Friday, July 23, 2010
Validation

    Trigger validation by marking a JavaBean parameter as @Valid
      • The JavaBean will be passed to a Validator for validation
      • JSR-303 auto-configured if a provider is present on the classpath

    Binding and validation errors can be trapped and introspected by
      declaring a BindingResult parameter
      • Must follow the JavaBean parameter in the method signature
      • Errors automatically exported in the model when rendering views
      • Not supported with other request parameter types (@RequestBody, etc)




                                                                               21

Friday, July 23, 2010
Generating Responses
    Return a POJO annotated with @ResponseBody
      • POJO marshaled as the body of the response
      • Converted to a representation based on Accept header
      • Default converters auto-configured for JSON, XML, Atom, etc

         or
    Return a logical view name
      • ViewResolver -> View layer kicks in
      • View abstractions for numerous templating/rendering technologies (i.e., JSP,
         Tiles, Freemarker, Excel, PDF, Atom, JSON, XML)
      • ContentNegotiatingViewResolver can chain ViewResolvers and select based on
         Accept header

         or
    Return a new ResponseEntity<T> object
      • More powerful, low-level; allows for setting custom response headers and status

                                                                                       22

Friday, July 23, 2010
Typical Controller Example

                                HotelsController

        @RequestMapping("/hotels")
        public @ResponseBody List<Hotel> getHotels(@Valid SearchCriteria criteria) {
  	     	    return travelService.findHotels(criteria);
  	     }

        @RequestMapping("/hotels/{id}")
        public @ResponseBody Hotel getHotel(@PathVariable Long id) {
  	     	    return travelService.findHotelById(id);
        }

        @RequestMapping(value = "/hotels", method = RequestMethod.POST)
        public String addHotel(@Valid Hotel hotel) {
  	     	    hotel = travelService.addHotel(hotel);
  	     	    return "redirect:/hotels/" + hotel.getId();
        }




                                                                                   23

Friday, July 23, 2010
Pluggability

    Spring MVC allows you to customize just about any part of the
      request chain
      • HttpMessageConverters
      • HandlerInterceptors
      • ExceptionHandlers
      • ViewResolvers
      • HandlerMappings
      • HandlerAdapters
      • WebArgumentResolvers
      • TypeConverters
      • Validators
      • ...and more




                                                                     24

Friday, July 23, 2010
Demo




                        25

Friday, July 23, 2010
The Spring Web Stack

                                                       Spring
                          Spring Faces
                                                 BlazeDS Integration

                         Spring            Spring
                                                       Spring Security
                        Web Flow         JavaScript


                             Spring Framework and Spring MVC




                                                                         26

Friday, July 23, 2010
Goals of Spring JavaScript

    Encapsulate use of Dojo for common enterprise use cases
      • Ajax (fragment rendering support)
      • Client-side validation

    Promotes progressive enhancement
      • Robust in the face of JavaScript failure
      • Maximizes potential audience
      • Accessibility




                                                               27

Friday, July 23, 2010
Working with the Spring JavaScript API

    Use API to apply decorations to HTML elements

    Different types of decorations
      • WidgetDecoration
      • AjaxEventDecoration
      • ValidateAllDecoration




                                                     28

Friday, July 23, 2010
Ajax with Partial Rendering



                    <a id="moreResultsLink” href="search?q=$
                      {criteria.q}&page=${criteria.page+1}">
                        More Results
                    </a>
                    <script type="text/javascript">
                        Spring.addDecoration(new Spring.AjaxEventDecoration({
                          elementId: "moreResultsLink",
                          event: "onclick",
                          params: {
                              fragments: "searchResults”
                          }
                        })); Name of tile to re-render on server
                    </script>
                                   No callback function necessary to link in response




                                                                                        29

Friday, July 23, 2010
Form Validation




             <form:input path="creditCard"/>
             <script type="text/javascript">
                Spring.addDecoration(new Spring.ElementDecoration({
                   elementId : "creditCard",
                   widgetType : "dijit.form.ValidationTextBox",
                   widgetAttrs : {
                        required : true,
                        invalidMessage : "A 16-digit number is required.",
                        regExp : "[0-9]{16}”
                   }
                }));
             </script>




                                                                             30

Friday, July 23, 2010
Future of Spring JavaScript

    Resource Handling and Partial Rendering ideas will be incorporated
      directly into Spring 3.1

    Client-side bits will be incorporated into Spring Roo
      • Much better platform for realizing some of the original ideas (i.e., generation of
         client-side validation based on Java model)
         • Can support multiple libraries through Spring Roo Addons


    Will continue to support the API in Spring Web Flow releases




                                                                                             31

Friday, July 23, 2010
The Spring Web Stack

                                                       Spring
                          Spring Faces
                                                 BlazeDS Integration

                         Spring            Spring
                                                       Spring Security
                        Web Flow         JavaScript


                             Spring Framework and Spring MVC




                                                                         32

Friday, July 23, 2010
Spring Web Flow

    For implementing stateful flows
      • Reusable multi-step user dialogs

    Plugs into Spring MVC

    Spring Web Flow 2 available now
      • Incorporates lessons learned from 1.0
      • Offers many new features




                                                33

Friday, July 23, 2010
Web Flow Sweet Spot




                         34

Friday, July 23, 2010
New Web Flow 2 Features

      • Ajax support
         • Partial page re-rendering in flow DSL

      • Spring security integration

      • Flow-managed persistence

      • Convention-over-configuration
         • View rendering
         • Data binding and validation




                                                   35

Friday, July 23, 2010
Spring Web Flow 3 - @Flow

      • Extends @Controller model

      • Define stateful UI flow control using plain Java

      • Builds on Spring Web Flow infrastructure




                                                           36

Friday, July 23, 2010
@Flow Example
       @Flow
       public class BookHotel {

            private Booking booking;

            @Autowired private transient BookingService booking;

            public State start(@Input Long hotelId, Principal user) {
                booking = bookingService.createBooking(hotelId, user);
                return new EnterBookingDetails();
            }

            private class EnterBookingDetails extends ViewState {
               @Transition
               State next() { return new ReviewBooking() };
            }

            private class ReviewBooking extends ViewState {}

                                                                         37

Friday, July 23, 2010
The Spring Web Stack

                                                        Spring
                          Spring Faces
                                                  BlazeDS Integration

                         Spring            Spring
                                                        Spring Security
                        Web Flow         JavaScript


                             Spring Framework and Spring MVC




                                                                          38

Friday, July 23, 2010
Spring BlazeDS Integration

    Spring’s Adobe Flex integration project

      • Connects Flex clients to Spring-managed services
         • Using BlazeDS MessageBroker boot-strapped by Spring

      • Makes Flex natural fit in a Spring environment
         • Uses Spring XML namespace for simplified setup
         • Reduces the need for BlazeDS-specific config




                                                                 39

Friday, July 23, 2010
Spring BlazeDS Integration

      • Expose Spring beans as Remoting destinations (for RPC style interaction)
         • <flex:remoting-destination> or @RemotingDestination

      • Message-style communication through native BlazeDS messaging, JMS, and
         Spring Integration channels
         • enables server-side push

      • Integrate Spring Security to secure Flex apps
         • <flex:secured>




                                                                                   40

Friday, July 23, 2010
Demo




                        41

Friday, July 23, 2010
The Future

    Other ideas being considered for Spring 3.1
      • Incorporation of Servlet 3.0 features (auto-config, async servlets, etc.)
      • HTML5 support in the JSP tag library
      • Offline caching support
      • Cometd and WebSocket support
      • Server-sent events

    SpringOne 2010 in Chicago (www.springone2gx.com)
      • See lots more content on Spring Roo, Spring MVC, and deep-dives into mobile
         and social integration




                                                                                      42

Friday, July 23, 2010
Resources

    http://www.springsource.org

    http://www.springsource.org/roo

    http://www.springsource.org/webflow

    http://www.springsource.org/spring-flex

    http://blog.springsource.com/2010/07/22/spring-mvc-3-showcase




                                                                     43

Friday, July 23, 2010
Thank you!




                                     44

Friday, July 23, 2010

More Related Content

PDF
Comparing JSF, Spring MVC, Stripes, Struts 2, Tapestry and Wicket
PDF
The 2014 Decision Makers Guide to Java Web Frameworks
PDF
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
PDF
GWT Overview And Feature Preview - SV Web JUG - June 16 2009
PPTX
Web Frameworks
PDF
Running your Java EE 6 applications in the Cloud @ Silicon Valley Code Camp 2010
PDF
Java EE 7: Boosting Productivity and Embracing HTML5
PDF
soft-shake.ch - Introduction to HTML5
Comparing JSF, Spring MVC, Stripes, Struts 2, Tapestry and Wicket
The 2014 Decision Makers Guide to Java Web Frameworks
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
GWT Overview And Feature Preview - SV Web JUG - June 16 2009
Web Frameworks
Running your Java EE 6 applications in the Cloud @ Silicon Valley Code Camp 2010
Java EE 7: Boosting Productivity and Embracing HTML5
soft-shake.ch - Introduction to HTML5

What's hot (7)

PDF
Eclipse RT projects Gemini web and Virgo par Steve Powell
PDF
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
PDF
Grizzly 20080925 V2
PDF
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
PPTX
Apache Wicket
PDF
Nuxeo 5.2 Glassfish
PDF
Apache Wicket Web Framework
Eclipse RT projects Gemini web and Virgo par Steve Powell
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Grizzly 20080925 V2
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
Apache Wicket
Nuxeo 5.2 Glassfish
Apache Wicket Web Framework
Ad

Similar to Building Next-Gen Web Applications with the Spring 3 Web Stack (20)

PPT
Spring 3.1: a Walking Tour
KEY
Multi client Development with Spring
PPTX
Spring Framework 3.2 - What's New
KEY
Multi Client Development with Spring
KEY
A Walking Tour of (almost) all of Springdom
PDF
Extending spring
PDF
Spring Mvc
PDF
The spring 32 update final
PDF
Extending Spring for Custom Usage
ODP
Spring Mvc,Java, Spring
PPTX
Enterprise Spring Building Scalable Applications
PPTX
Spring Web Presentation 123143242341234234
PDF
JavaOne India 2011 - Servlets 3.0
PDF
REST based web applications with Spring 3
PPTX
Spring Test Framework
PPT
Spring - a framework written by developers
PDF
Spring 3.1 in a Nutshell
ODP
Enterprise Java in 2012 and Beyond, by Juergen Hoeller
PDF
Comparing JVM Web Frameworks - Devoxx 2010
PDF
Testing Web Apps with Spring Framework 3.2
Spring 3.1: a Walking Tour
Multi client Development with Spring
Spring Framework 3.2 - What's New
Multi Client Development with Spring
A Walking Tour of (almost) all of Springdom
Extending spring
Spring Mvc
The spring 32 update final
Extending Spring for Custom Usage
Spring Mvc,Java, Spring
Enterprise Spring Building Scalable Applications
Spring Web Presentation 123143242341234234
JavaOne India 2011 - Servlets 3.0
REST based web applications with Spring 3
Spring Test Framework
Spring - a framework written by developers
Spring 3.1 in a Nutshell
Enterprise Java in 2012 and Beyond, by Juergen Hoeller
Comparing JVM Web Frameworks - Devoxx 2010
Testing Web Apps with Spring Framework 3.2
Ad

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Electronic commerce courselecture one. Pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Approach and Philosophy of On baking technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Getting Started with Data Integration: FME Form 101
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Machine learning based COVID-19 study performance prediction
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Advanced methodologies resolving dimensionality complications for autism neur...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Digital-Transformation-Roadmap-for-Companies.pptx
A Presentation on Artificial Intelligence
Electronic commerce courselecture one. Pdf
1. Introduction to Computer Programming.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Unlocking AI with Model Context Protocol (MCP)
MIND Revenue Release Quarter 2 2025 Press Release
Programs and apps: productivity, graphics, security and other tools
Approach and Philosophy of On baking technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Dropbox Q2 2025 Financial Results & Investor Presentation
Group 1 Presentation -Planning and Decision Making .pptx
Getting Started with Data Integration: FME Form 101
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Machine learning based COVID-19 study performance prediction
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Accuracy of neural networks in brain wave diagnosis of schizophrenia

Building Next-Gen Web Applications with the Spring 3 Web Stack

  • 1. Building Next-Gen Web Applications with the Spring 3.0 Web Stack Jeremy Grelle (@jeremyg484) Senior Member Technical Staff (a.k.a, Open Source Web Dude) SpringSource a division of VMware © 2010 SpringSource, A division of VMware. All rights reserved Friday, July 23, 2010
  • 2. Battling the rising complexity of web application development by building on a lightweight Spring foundation. 2 Friday, July 23, 2010
  • 3. Next-Gen? - The Modern Web Dilemma  Web application requirement complexity continues to rise • How do we manage this complexity? • How do we expose our services to the largest possible audience? • How do we give users the best possible experience in the shortest amount of time? 3 Friday, July 23, 2010
  • 4. The Spring Web Stack - Simplicity and Power  The Spring Web Stack gives you: • unified programming model • multiple client types served with the same foundation • adaptability - the right approach (i.e., stateless, stateful) for the given use case 4 Friday, July 23, 2010
  • 5. The Spring Web Stack Spring Spring Faces BlazeDS Integration Spring Spring Spring Security Web Flow JavaScript Spring Framework and Spring MVC 5 Friday, July 23, 2010
  • 6. Web Stack Components  Spring Framework and Spring MVC • The foundation for all other components  Spring JavaScript • Ajax integration  Spring Web Flow • Framework for stateful web conversation 6 Friday, July 23, 2010
  • 7. Web Stack Components (cont.)  Spring Security • Security framework  Spring Faces • Integration with JavaServer Faces via Web Flow  Spring BlazeDS Integration • Integration with Adobe Flex clients 7 Friday, July 23, 2010
  • 8. Next-Gen? - Productivity: More Important than Ever Before  Must resolve first obstacle to Java in the cloud  Expectations are higher than ever before  Success of Ruby on Rails et al has raised the bar for building simpler applications  Developer choice crucial in determining cloud • Cloud apps often new • Often start simple  Java/JVM technologies perceived as complex CONFIDENTIAL 8 Friday, July 23, 2010
  • 9. Increasing Productivity: The Opinionation Pyramid Opinionated, Productive  Ideal is to build on top of powerful, extensible layers Grails/ Roo  No need to move to Spring introduce new runtime Servlet/other specifications  Never hit a wall JVM Choice, Power CONFIDENTIAL 9 Friday, July 23, 2010
  • 10. Grails  The most popular rapid development framework for the JVM  Solutions built on solid foundations CONFIDENTIAL SpringOne 2GX 2009. All rights reserved. Do not distribute without permission. 10 Friday, July 23, 2010
  • 11. Spring Roo  Higher Java productivity  Familiar Java • Roo uses the Java APIs and standards you already know and trust.  Usable and learnable • Roo features an extremely high level of usability and an advanced shell  Trusted Spring Stack • Roo has no runtime – It’s just Spring  Easy Roo removal • Roo can be easily removed from a user project in under five minutes. CONFIDENTIAL 11 Friday, July 23, 2010
  • 12. Getting Started  Create a new Spring MVC project from a template • Most use Roo to do this, either from an IDE like STS or the command-line  Typical setup:  One DispatcherServlet registered in web.xml • FrontController that dispatches web requests to your application logic • Generally the “default servlet” mapped to “/”  Two Spring Containers (or ApplicationContexts) instantiated • 1 “root” context to host “shared resources” required by Servlets / Filters • 1 “web” context to host local application components delegated to by the DispatcherServlet • Your application components are typically discovered via classpath scanning 12 Friday, July 23, 2010
  • 13. Demo 13 Friday, July 23, 2010
  • 14. The Spring Web Stack Spring Spring Faces BlazeDS Integration Spring Spring Spring Security Web Flow JavaScript Spring Framework and Spring MVC 14 Friday, July 23, 2010
  • 15. Introduction to the MVC programming model  DispatcherServlet requests are mapped to @Controller methods • @RequestMapping annotation used to define mapping rules • Method parameters used to obtain request input • Method return values used to generate responses  Simplest possible @Controller: @Controller public class SimpleController { @RequestMapping("/simple") public @ResponseBody String simple() { return "Hello world!"; } } 15 Friday, July 23, 2010
  • 16. Mapping Requests  By path • @RequestMapping(“path”)  By HTTP method • @RequestMapping(“path”, method=RequestMethod.GET) • POST, PUT, DELETE, OPTIONS, and TRACE are are also supported  By presence of query parameter • @RequestMapping(“path”, method=RequestMethod.GET, params=”foo”) • Negation also supported: params={ “foo”, “!bar” })  By presence of request header • @RequestMapping(“path”, header=”content-type=text/*”) • Negation also supported 16 Friday, July 23, 2010
  • 17. Mapping Requests (2)  Simplest possible @Controller revisited @Controller public class SimpleControllerRevisited { @RequestMapping(value="/simple/revisited", method=RequestMethod.GET, headers="Accept=text/plain") public @ResponseBody String simple() { return "Hello world revisited!"; } } 17 Friday, July 23, 2010
  • 18. Request Mapping at the Class Level  @RequestMapping can be used at the class level • Concise way to map all requests within a path to a @Controller @Controller @RequestMapping("/accounts/*") public class AccountsController { @RequestMapping("active") public @ResponseBody List<Account> active() { ... } @RequestMapping("inactive") public @ResponseBody List<Account> inactive() { ... } } 18 Friday, July 23, 2010
  • 19. Obtaining Request Data  Obtain request data by declaring method arguments • A query parameter value • @RequestParam(“name”) • A group of query parameter values • A custom JavaBean with a getName()/setName() pair for each parameter • A path element value • @PathVariable(“var”) • A request header value • @RequestHeader(“name”) • A cookie value • @CookieValue(“name”) • The request body • @RequestBody • The request body and any request header • HttpEntity<T> 19 Friday, July 23, 2010
  • 20. Injecting Standard Objects  A number of “standard arguments” can also be injected • Simply declare the argument you need as a method param  HttpServletRequest (or its more portable WebRequest wrapper)  Principal  Locale  InputStream  Reader  HttpServletResponse  OutputStream  Writer  HttpSession 20 Friday, July 23, 2010
  • 21. Validation  Trigger validation by marking a JavaBean parameter as @Valid • The JavaBean will be passed to a Validator for validation • JSR-303 auto-configured if a provider is present on the classpath  Binding and validation errors can be trapped and introspected by declaring a BindingResult parameter • Must follow the JavaBean parameter in the method signature • Errors automatically exported in the model when rendering views • Not supported with other request parameter types (@RequestBody, etc) 21 Friday, July 23, 2010
  • 22. Generating Responses  Return a POJO annotated with @ResponseBody • POJO marshaled as the body of the response • Converted to a representation based on Accept header • Default converters auto-configured for JSON, XML, Atom, etc or  Return a logical view name • ViewResolver -> View layer kicks in • View abstractions for numerous templating/rendering technologies (i.e., JSP, Tiles, Freemarker, Excel, PDF, Atom, JSON, XML) • ContentNegotiatingViewResolver can chain ViewResolvers and select based on Accept header or  Return a new ResponseEntity<T> object • More powerful, low-level; allows for setting custom response headers and status 22 Friday, July 23, 2010
  • 23. Typical Controller Example HotelsController @RequestMapping("/hotels") public @ResponseBody List<Hotel> getHotels(@Valid SearchCriteria criteria) { return travelService.findHotels(criteria); } @RequestMapping("/hotels/{id}") public @ResponseBody Hotel getHotel(@PathVariable Long id) { return travelService.findHotelById(id); } @RequestMapping(value = "/hotels", method = RequestMethod.POST) public String addHotel(@Valid Hotel hotel) { hotel = travelService.addHotel(hotel); return "redirect:/hotels/" + hotel.getId(); } 23 Friday, July 23, 2010
  • 24. Pluggability  Spring MVC allows you to customize just about any part of the request chain • HttpMessageConverters • HandlerInterceptors • ExceptionHandlers • ViewResolvers • HandlerMappings • HandlerAdapters • WebArgumentResolvers • TypeConverters • Validators • ...and more 24 Friday, July 23, 2010
  • 25. Demo 25 Friday, July 23, 2010
  • 26. The Spring Web Stack Spring Spring Faces BlazeDS Integration Spring Spring Spring Security Web Flow JavaScript Spring Framework and Spring MVC 26 Friday, July 23, 2010
  • 27. Goals of Spring JavaScript  Encapsulate use of Dojo for common enterprise use cases • Ajax (fragment rendering support) • Client-side validation  Promotes progressive enhancement • Robust in the face of JavaScript failure • Maximizes potential audience • Accessibility 27 Friday, July 23, 2010
  • 28. Working with the Spring JavaScript API  Use API to apply decorations to HTML elements  Different types of decorations • WidgetDecoration • AjaxEventDecoration • ValidateAllDecoration 28 Friday, July 23, 2010
  • 29. Ajax with Partial Rendering <a id="moreResultsLink” href="search?q=$ {criteria.q}&page=${criteria.page+1}"> More Results </a> <script type="text/javascript"> Spring.addDecoration(new Spring.AjaxEventDecoration({ elementId: "moreResultsLink", event: "onclick", params: { fragments: "searchResults” } })); Name of tile to re-render on server </script> No callback function necessary to link in response 29 Friday, July 23, 2010
  • 30. Form Validation <form:input path="creditCard"/> <script type="text/javascript"> Spring.addDecoration(new Spring.ElementDecoration({ elementId : "creditCard", widgetType : "dijit.form.ValidationTextBox", widgetAttrs : { required : true, invalidMessage : "A 16-digit number is required.", regExp : "[0-9]{16}” } })); </script> 30 Friday, July 23, 2010
  • 31. Future of Spring JavaScript  Resource Handling and Partial Rendering ideas will be incorporated directly into Spring 3.1  Client-side bits will be incorporated into Spring Roo • Much better platform for realizing some of the original ideas (i.e., generation of client-side validation based on Java model) • Can support multiple libraries through Spring Roo Addons  Will continue to support the API in Spring Web Flow releases 31 Friday, July 23, 2010
  • 32. The Spring Web Stack Spring Spring Faces BlazeDS Integration Spring Spring Spring Security Web Flow JavaScript Spring Framework and Spring MVC 32 Friday, July 23, 2010
  • 33. Spring Web Flow  For implementing stateful flows • Reusable multi-step user dialogs  Plugs into Spring MVC  Spring Web Flow 2 available now • Incorporates lessons learned from 1.0 • Offers many new features 33 Friday, July 23, 2010
  • 34. Web Flow Sweet Spot 34 Friday, July 23, 2010
  • 35. New Web Flow 2 Features • Ajax support • Partial page re-rendering in flow DSL • Spring security integration • Flow-managed persistence • Convention-over-configuration • View rendering • Data binding and validation 35 Friday, July 23, 2010
  • 36. Spring Web Flow 3 - @Flow • Extends @Controller model • Define stateful UI flow control using plain Java • Builds on Spring Web Flow infrastructure 36 Friday, July 23, 2010
  • 37. @Flow Example @Flow public class BookHotel { private Booking booking; @Autowired private transient BookingService booking; public State start(@Input Long hotelId, Principal user) { booking = bookingService.createBooking(hotelId, user); return new EnterBookingDetails(); } private class EnterBookingDetails extends ViewState { @Transition State next() { return new ReviewBooking() }; } private class ReviewBooking extends ViewState {} 37 Friday, July 23, 2010
  • 38. The Spring Web Stack Spring Spring Faces BlazeDS Integration Spring Spring Spring Security Web Flow JavaScript Spring Framework and Spring MVC 38 Friday, July 23, 2010
  • 39. Spring BlazeDS Integration  Spring’s Adobe Flex integration project • Connects Flex clients to Spring-managed services • Using BlazeDS MessageBroker boot-strapped by Spring • Makes Flex natural fit in a Spring environment • Uses Spring XML namespace for simplified setup • Reduces the need for BlazeDS-specific config 39 Friday, July 23, 2010
  • 40. Spring BlazeDS Integration • Expose Spring beans as Remoting destinations (for RPC style interaction) • <flex:remoting-destination> or @RemotingDestination • Message-style communication through native BlazeDS messaging, JMS, and Spring Integration channels • enables server-side push • Integrate Spring Security to secure Flex apps • <flex:secured> 40 Friday, July 23, 2010
  • 41. Demo 41 Friday, July 23, 2010
  • 42. The Future  Other ideas being considered for Spring 3.1 • Incorporation of Servlet 3.0 features (auto-config, async servlets, etc.) • HTML5 support in the JSP tag library • Offline caching support • Cometd and WebSocket support • Server-sent events  SpringOne 2010 in Chicago (www.springone2gx.com) • See lots more content on Spring Roo, Spring MVC, and deep-dives into mobile and social integration 42 Friday, July 23, 2010
  • 43. Resources  http://www.springsource.org  http://www.springsource.org/roo  http://www.springsource.org/webflow  http://www.springsource.org/spring-flex  http://blog.springsource.com/2010/07/22/spring-mvc-3-showcase 43 Friday, July 23, 2010
  • 44. Thank you! 44 Friday, July 23, 2010