spring mvc 3

45
Building Web Applications with Spring 3.0 by Bob McCune www.bobmccune.com 1 Monday, May 18, 2009

Upload: parasjain01

Post on 10-Apr-2015

18.608 views

Category:

Documents


4 download

DESCRIPTION

This document was created by Bob McCune and downloaded from http://www.intertech.com/UserGroups/JUGPresentation.aspx?TopicID=135. All the rights of the documents lies with Bob.

TRANSCRIPT

Page 1: Spring MVC 3

Building Web Applications with Spring 30by Bob McCune

wwwbobmccunecom

1Monday May 18 2009

Agenda

Spring MVC Overview

Spring MVC Infrastructure

Developing Controllers

RESTful Web Services

Demo

2Monday May 18 2009

Spring MVC Overview

3Monday May 18 2009

What is MVC

Model

Domain-specific data and processing logic

Entities services repositories etc

View

User-facing presentation

JSPs VelocityFreemarker Templates XSLT etc

Controller

Mediator between model and view

Responsible for routing requests and responses

4Monday May 18 2009

What is Spring MVC

Core web component of the Spring Framework

Foundation of Springrsquos web strategy

Similar to Struts but with improvements

Better separation of concerns

Robust data binding and validation

Customizable type coercion with property editors

Supports wide variety of view technologies

JSPJSTL XMLXSLT Freemarker Velocity PDF etc

Significantly enhanced in 25 release and further refined in 30

5Monday May 18 2009

Spring MVC Basics

6Monday May 18 2009

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 2: Spring MVC 3

Agenda

Spring MVC Overview

Spring MVC Infrastructure

Developing Controllers

RESTful Web Services

Demo

2Monday May 18 2009

Spring MVC Overview

3Monday May 18 2009

What is MVC

Model

Domain-specific data and processing logic

Entities services repositories etc

View

User-facing presentation

JSPs VelocityFreemarker Templates XSLT etc

Controller

Mediator between model and view

Responsible for routing requests and responses

4Monday May 18 2009

What is Spring MVC

Core web component of the Spring Framework

Foundation of Springrsquos web strategy

Similar to Struts but with improvements

Better separation of concerns

Robust data binding and validation

Customizable type coercion with property editors

Supports wide variety of view technologies

JSPJSTL XMLXSLT Freemarker Velocity PDF etc

Significantly enhanced in 25 release and further refined in 30

5Monday May 18 2009

Spring MVC Basics

6Monday May 18 2009

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 3: Spring MVC 3

Spring MVC Overview

3Monday May 18 2009

What is MVC

Model

Domain-specific data and processing logic

Entities services repositories etc

View

User-facing presentation

JSPs VelocityFreemarker Templates XSLT etc

Controller

Mediator between model and view

Responsible for routing requests and responses

4Monday May 18 2009

What is Spring MVC

Core web component of the Spring Framework

Foundation of Springrsquos web strategy

Similar to Struts but with improvements

Better separation of concerns

Robust data binding and validation

Customizable type coercion with property editors

Supports wide variety of view technologies

JSPJSTL XMLXSLT Freemarker Velocity PDF etc

Significantly enhanced in 25 release and further refined in 30

5Monday May 18 2009

Spring MVC Basics

6Monday May 18 2009

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 4: Spring MVC 3

What is MVC

Model

Domain-specific data and processing logic

Entities services repositories etc

View

User-facing presentation

JSPs VelocityFreemarker Templates XSLT etc

Controller

Mediator between model and view

Responsible for routing requests and responses

4Monday May 18 2009

What is Spring MVC

Core web component of the Spring Framework

Foundation of Springrsquos web strategy

Similar to Struts but with improvements

Better separation of concerns

Robust data binding and validation

Customizable type coercion with property editors

Supports wide variety of view technologies

JSPJSTL XMLXSLT Freemarker Velocity PDF etc

Significantly enhanced in 25 release and further refined in 30

5Monday May 18 2009

Spring MVC Basics

6Monday May 18 2009

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 5: Spring MVC 3

What is Spring MVC

Core web component of the Spring Framework

Foundation of Springrsquos web strategy

Similar to Struts but with improvements

Better separation of concerns

Robust data binding and validation

Customizable type coercion with property editors

Supports wide variety of view technologies

JSPJSTL XMLXSLT Freemarker Velocity PDF etc

Significantly enhanced in 25 release and further refined in 30

5Monday May 18 2009

Spring MVC Basics

6Monday May 18 2009

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 6: Spring MVC 3

Spring MVC Basics

6Monday May 18 2009

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 7: Spring MVC 3

DispatcherServlet

Handler Mapping

View Resolver

ControllerRequest

Request

Request

View Name

Response

View

Controller

ModelAndView

View

ModelResponse

1

2

3

4

5

RequestResponse Handling

7Monday May 18 2009

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 8: Spring MVC 3

DispatcherServlet

Front Controller implementation in Spring MVC

Handles incoming request and dispatches to appropriate handler

Coordinates communication between infrastructural components

Wired as standard servlet in webxml

Upon initialization looks for servletname-servletxml

Default values defined in DispatcherServletpropertiesOverriding defaults replaces default values

8Monday May 18 2009

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 9: Spring MVC 3

Configuring webxml

ltservletgt ltservlet-namegtspringltservlet-namegt ltservlet-classgt orgspringframeworkwebservletDispatcherServlet ltservlet-classgt ltload-on-startupgt1ltload-on-startupgtltservletgt

ltservlet-mappinggt ltservlet-namegtspringltservlet-namegt lturl-patterngtv3lturl-patterngtltservlet-mappinggt

Servlet Configuration

Servlet Mapping

DispatcherServlet finds context configuration

based on name

9Monday May 18 2009

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 10: Spring MVC 3

HandlerMapping

Defines interface to select appropriate handler (Controller)

DispatcherServlet consults HandlerMapping collection to locate appropriate controller

Interceptors can be applied to customize prepost processing

Common implementations

BeanNameUrlHandlerMapping Maps requests based on bean names

SimpleUrlHandlerMapping Maps request URLs to Controller beans

ControllerClassNameHandlerMapping Auto generates mappings by class name

DefaultAnnotationHandlerMapping Maps request based on annotations

10Monday May 18 2009

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 11: Spring MVC 3

Controller

Controller defines the interface to handle and process requests

Provides access to the HttpServletRequest and HttpServletResponse

Returns ModelAndView

Composite data holder for the data model and a view

Model is typically a Map variant

View can be logical view name or actual View instance

public ModelAndView handleRequest(HttpServletRequest request HttpServletResponse response) throws Exception

Forward request to ldquoartists listrdquo viewreturn new ModelAndView(ldquoartistsrdquo)

11Monday May 18 2009

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 12: Spring MVC 3

ViewResolver

ViewResolver defines the interface to select an appropriate View for the response

ViewResolver instances can be chained together into an ordered collection

Common implementations include

InternalResourceViewResolver

ResourceBundleViewResolver

XmlViewResolver

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgtltbeangt

12Monday May 18 2009

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 13: Spring MVC 3

View

Defines the interface for objects rendering a client response

Iterates through the values in the model to generate response

Framework provides a wide variety of View choices

Common Web View

JstlView FreemarkerView VelocityView XsltView

Special Format View

AbsractExcelView AbstractPdfView JasperReportsView

New Views in Spring 30

MarshallingView AbstractAtomFeedView AbstractRssFeedView

New in 30

13Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 14: Spring MVC 3

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=artistController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=genreController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

14Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 15: Spring MVC 3

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

15Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 16: Spring MVC 3

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

16Monday May 18 2009

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 17: Spring MVC 3

spring-servletxml

ltbeansgt ltbean id=handlerMapping class=orgspringframeworkwebservlethandlerSimpleUrlHandlerMappinggt ltproperty name=mappingsgt ltpropsgt ltprop key=v3genreshtmlgtgenreControllerltpropgt ltprop key=v3artistshtmlgtartistControllerltpropgt ltpropsgt ltpropertygt ltbeangt ltbean id=genreController class=commccuneosspringwebcontrollerArtistControllergt

ltbean id=artistsController class=commccuneosspringwebcontrollerGenreControllergt

ltbean class=orgspringframeworkwebservletviewInternalResourceViewResolvergt ltproperty name=prefix value=WEB-INFjspgt ltproperty name=suffix value=jspgt ltbeangt ltbeansgt

17Monday May 18 2009

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 18: Spring MVC 3

Developing Spring MVCControllers

18Monday May 18 2009

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 19: Spring MVC 3

Controller

Controllers historically built on Controller interface

Specialized implementations included

Simple Form Controllers

Form processing lifecycle

Databinding and validation

Wizard Form Controllers

Multi-page navigation

Multi-action Controllers

Grouped related stateless operations

19Monday May 18 2009

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 20: Spring MVC 3

Controller

AbstractController

BaseCommandControllerMultiActionController

AbstractCommandController

AbstractFormController

SimpleFormController

AbstractUrlViewController

Controller Hierarchy

Deprecated

20Monday May 18 2009

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 21: Spring MVC 3

Controller to Controller

Designates a class as a Spring MVC ControllerRemoves the need to implement or extend Spring-specific classes

Controller stereotype automatically be picked up if using component scanningltcontextcomponent-scan base-package=comcompanyspringweb gt

Flexible method signatures

No need to implementoverride lifecycle methods

Can eliminate dependencies on Servlet API

No need to ldquomock outrdquo dependencies in unit tests

21Monday May 18 2009

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 22: Spring MVC 3

Flexible Method Arguments

Method signatures are very flexible

Arguments can be

Servlet types HttpServletRequest HttpServletResponse HttpSession

WebRequest wrapper over Servlet specifics

IO types InputStream OutputStream Reader Writer

Model types Model ModelMap Map

Model attributes Request parameters

Locale

22Monday May 18 2009

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 23: Spring MVC 3

Flexible Return Types

ModelAndView Wraps model and View or logical view name

Model or Map Return model with view implicitly defined

Will use RequestToViewNameTranslator

View View instance to be used to render response

String Interpreted as logical view name

void Can return void if Controller handles response

Any object Will be used as single model value

23Monday May 18 2009

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 24: Spring MVC 3

RequestMapping

Used to map URL patterns to controllers

Can be applied at either a class andor method level

Multi-action controllers commonly defined at method level

Form controllers applied at class level with method level annotations used to narrow request to particular type

Greater mapping flexibility than previous releases

24Monday May 18 2009

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 25: Spring MVC 3

RequestParam13

Used to bind request parameters to method parameters

Limits or removes needs to rely on Servlet API

RequestParam designates a required parameter

Can be made optional with required=false

public class EditController

public String configure( int id ModelMap model) modelput(servicegetContact(id))return ldquoeditrdquo

RequestMapping(method = RequestMethodGET)RequestParam(id)

ControllerRequestMapping(editdo)

25Monday May 18 2009

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 26: Spring MVC 3

ModelAttributeSessionAttribute

Used to map model data into controller

Used at a method level to maps model attribute to method argument

No need to work directly with HttpServletRequest

Can also be used at method level to provide reference data

ModelAttribute is processed before RequestMappings so data is pre-populated before controller processing

Can use SessionAttribute to store and retrieve session data

26Monday May 18 2009

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 27: Spring MVC 3

InitBinder and WebBindingInitializer

Springrsquos data binding capabilities are one of the more compelling reasons to use Spring MVC

Built in support for all primitivewrapper types

Uses standard Java SE PropertyEditor instances for type coercion Can write custom editors for advanced binding

Custom editors can be mapped

Controller using the InitBinder annotation

Application level use implementation of WebBindingInitializer

New type conversion SPI and converter API

Provides Java 5 friendly data type converter strategy

New in 30

27Monday May 18 2009

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 28: Spring MVC 3

Convention Configuration

ControllerClassNameHandlerMappingAutomatically generates mapping based on Controller name

Removes ldquoControllerrdquo from name and lowercases resulting value

Eg ArtistController maps to artist

Model and ModelMapGenerates attribute names from model types

Artist produces ldquoartistrdquo attribute

ListltArtistgt produces ldquoartistListrdquo attribute

RequestToViewNameTranslatorGenerates logical view name from incoming request

Eg Request for httpserverartistshtml produces logical view name of ldquoartistsrdquo

28Monday May 18 2009

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 29: Spring MVC 3

REST Support

29Monday May 18 2009

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 30: Spring MVC 3

What is REST

REpresentational State Transfer

Lightweight resource-oriented architectural style

Unlike SOAP or XML-RPC is not a standard

Stateless cacheable scalable communication protocol

Uses standard HTTP methods to read and write data

Provides uniform interface for interacting with resources

Nouns used to represent resources artists albums etc

Verbs defined through standard HTTP methods

30Monday May 18 2009

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 31: Spring MVC 3

HTTP Methods

Resource interaction through standard HTTP methods

GET Gets a representation of resource Safe operation

POST Creates or updates resource

PUT Creates or updates resource Idempotent

DELETE Deletes a resource Idempotent

HEAD GET request without body Returns headers only

OPTIONS Discovery method to determine allows

31Monday May 18 2009

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 32: Spring MVC 3

Spring 30 REST Support

Builds on Spring 25rsquos Controller Model

Focuses on making it simple to expose and consume RESTful Web Services

Client-side access greatly simplified via RestTemplate

Server-side development enhanced with expanded request mappings and path variables

Provides competing approach to JAX-RS implementations

Jersey

RESTEasy

Restlet

32Monday May 18 2009

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 33: Spring MVC 3

URI Templates

RESTful services define resource locations through URIs

httpwwwhostcomordersorderId

Variable expansion would convert URI to

httpwwwhostcomorders8675309

Spring MVC implements URI Templates through its standard RequestMapping annotation

PathVariable annotation can extract template values from template variables

33Monday May 18 2009

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 34: Spring MVC 3

Mapping Requests

Uses standard Spring MVC RequestMapping annotation

Supports URI templates in path expressions

ControllerRequestMapping(artistsartistId)public class ArtistController

RequestMapping(method = RequestMethodPOST) public String create(Artist artist) return artist

RequestMapping(method = RequestMethodDELETE) public String delete(Long id) return artist

34Monday May 18 2009

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 35: Spring MVC 3

PathVariable

PathVariable maps URI template placeholders to argument values

Can use multiple PathVariable annotations

Values can be explicitly defined or inferred through debug info

Controllerpublic class AlbumController

RequestMapping(value = artistsartistIdalbumsalbumId method = RequestMethodGET) public Album getAlbum(PathVariable(artistId) Long artistId PathVariable(albumId) Long albumId) return servicefindAlbum(artistId albumId)

35Monday May 18 2009

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 36: Spring MVC 3

30 Controller Annotations

RequestHeader

Allows request headers to be bound to method arguments

CookieValue

Allows cookie values to be bound to method arguments

RequestBody

Allows binding request body to a method argument

Request body converted using HttpMethodConverter implementations

Implementations provided for converting byte arrays strings form values XML sources and JSON (forthcoming)

36Monday May 18 2009

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 37: Spring MVC 3

30 Views

Feed Views based on ROME project

AbstractRssFeedView renders an RSS feed

AbstractAtomFeedView renders an ATOM feed

MarshallingView returns XML representation using Springrsquos OXM framework

JacksonJsonView renders a response in JSON format

Currently only available in Spring JS project

Hopefully moved to core in final release

37Monday May 18 2009

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 38: Spring MVC 3

30 JSP Tags

Spring MVC JSP tags have been expanded to support REST

ltformformgt tag enhanced to support all HTTP methods

Browsers only support sending GET and POST requests

HiddenHttpMethodFilter converts specified method to hidden form field

ltspringurlgt tag enhanced to support URI templates

38Monday May 18 2009

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 39: Spring MVC 3

Content Negotiation

A key feature of REST is the ability to return multiple representations of a resource

XML HTML Text JSON etc

Two strategies for client to request content type

Specify the resourcersquos file extension

Set the appropriate Accept Header

Spring provides a ContentNegotiationViewResolverAllows mapping mime types to views

39Monday May 18 2009

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 40: Spring MVC 3

ETag Caching

ETags (entity tags) are a response header sent to determine if resource has changed

Unchanged content will return 304 Not Modified header

Spring supports shallow ETag caching with ShallowEtagHeaderFilter

Standard javaxservletFilter

Doesnrsquot save processing but does reduce bandwidth

Generates MD5 Hash for rendered view

Subsequent requests use this value in If-None-Match to compare if response should be resent

40Monday May 18 2009

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 41: Spring MVC 3

RestTemplate

Provides simplified client access to REST services

Interacting with resources often a single line of code

Conceptually similar to other Spring templates

JdbcTemplate

JmsTemplate

Provides callback methods to customize response handling

Uses ClientHttpRequest object based on javanetURLConnection and Jakarata Commons

Configurable with HttpMessageConverters

41Monday May 18 2009

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 42: Spring MVC 3

RestTemplate Methods

HTTP Method RestTemplate Method

GET

POST

PUT

DELETE

OPTIONS

HEAD

getForObject(String url ClassltTgt responseType String urlVariables)

postForLocation(String url Object request String urlVariables)

put(String url Object request String urlVariables)

delete(String url String urlVariables)

optionsForAllow(String url String urlVariables)

headForHeaders(String url Stringhellip urlVariables)

42Monday May 18 2009

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 43: Spring MVC 3

RestTemplate Example

RestTemplate template = new RestTemplate()

String URI = httplocalhost8080springmvcv3genresxmlSource source = templategetForObject(URI Sourceclass)

TransformerFactory factory = TransformerFactorynewInstance()Transformer transformer = factorynewTransformer()transformertransform(source new StreamResult(Systemout))

ltlistgt ltGenregt ltidgt1ltidgtltnamegtRockltnamegt ltidgt2ltidgtltnamegtJazzltnamegt ltidgt3ltidgtltnamegtCountryltnamegt ltGenregtltlistgt

Source

Produces

43Monday May 18 2009

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 44: Spring MVC 3

Demo

44Monday May 18 2009

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009

Page 45: Spring MVC 3

Summary

Spring MVC is a simple yet powerful Model 2 web framework

Controllers provide more flexibility that Controller hierarchy

Broad range of argument values

Any object type can be returned from controller method

RequestMappings enhanced to support RESTful services

URI Template variables extracted using PathVariable

New annotations provided to meet needs of REST developers

RestTemplate greatly simplifies client access to REST services

45Monday May 18 2009