diff --git a/spring-framework-reference/src/mvc.xml b/spring-framework-reference/src/mvc.xml
index 407b289d3dd..b9ca33f14ef 100644
--- a/spring-framework-reference/src/mvc.xml
+++ b/spring-framework-reference/src/mvc.xml
@@ -46,9 +46,10 @@
You cannot add advice to final methods when you use Spring MVC.
For example, you cannot add advice to the
- AbstractController.setSynchronizeOnSession() method. Refer to
- for more information on
- AOP proxies and why you cannot add advice to final methods.
+ AbstractController.setSynchronizeOnSession() method.
+ Refer to for more
+ information on AOP proxies and why you cannot add advice to final
+ methods.
In Spring Web MVC you can use any object as a command or
@@ -62,21 +63,21 @@
business objects.Spring's view resolution is extremely flexible. A
- Controller is typically responsible for preparing
- a model Map with data and selecting a view name but it
- can also write directly to the response stream and complete the request.
- View name resolution is highly configurable through file extension or Accept header
- content type negotiation, through bean names, a properties file,
- or even a custom ViewResolver
- implementation. The model (the M in MVC) is a
- Map interface, which allows for the
- complete abstraction of the view technology. You can integrate directly with
- template based rendering technologies such as JSP, Velocity and Freemarker,
- or directly generate XML, JSON, Atom, and many other types of content.
- The model Map is simply transformed into an
- appropriate format, such as JSP request attributes, a Velocity template
- model.
-
+ Controller is typically responsible for
+ preparing a model Map with data and selecting a
+ view name but it can also write directly to the response stream and
+ complete the request. View name resolution is highly configurable through
+ file extension or Accept header content type negotiation, through bean
+ names, a properties file, or even a custom
+ ViewResolver implementation. The model (the
+ M in MVC) is a Map interface, which allows
+ for the complete abstraction of the view technology. You can integrate
+ directly with template based rendering technologies such as JSP, Velocity
+ and Freemarker, or directly generate XML, JSON, Atom, and many other types
+ of content. The model Map is simply
+ transformed into an appropriate format, such as JSP request attributes, a
+ Velocity template model.
+
Features of Spring Web MVC
@@ -90,10 +91,10 @@
- Clear separation of roles. Each role —
+ Clear separation of roles. Each role —
controller, validator, command object, form object, model object,
DispatcherServlet, handler mapping, view
- resolver, and so on — can be fulfilled by a specialized
+ resolver, and so on — can be fulfilled by a specialized
object.
@@ -214,7 +215,7 @@
The DispatcherServletSpring's web MVC framework is, like many other web MVC frameworks,
- request-driven, designed around a central servlet that dispatches requests
+ request-driven, designed around a central Servlet that dispatches requests
to controllers and offers other functionality that facilitates the
development of web applications. Spring's
DispatcherServlet however, does more than just
@@ -237,8 +238,8 @@
-
The request processing workflow in Spring Web MVC
- (high level)
+
The request processing workflow in Spring Web MVC (high
+ level)
The DispatcherServlet is an actual
@@ -247,7 +248,7 @@
the web.xml of your web application. You need to map
requests that you want the DispatcherServlet to
handle, by using a URL mapping in the same web.xml
- file. This is standard J2EE servlet configuration; the following example
+ file. This is standard J2EE Servlet configuration; the following example
shows such a DispatcherServlet declaration and
mapping:
@@ -267,9 +268,10 @@
</web-app>
In the preceding example, all requests startig with
- /example will be handled by the DispatcherServlet
- instance named example. This is only the first step in
- setting up Spring Web MVC. You
+ /example will be handled by the
+ DispatcherServlet instance named
+ example. This is only the first step in setting up
+ Spring Web MVC. You
now need to configure the various beans used by the Spring Web MVC
framework (over and above the DispatcherServlet
itself).
@@ -282,7 +284,7 @@
the beans already defined in the root
WebApplicationContext. These inherited
beans can be overridden in the servlet-specific scope, and you can define
- new scope-specific beans local to a given servlet instance.
+ new scope-specific beans local to a given Servlet instance.
@@ -307,7 +309,7 @@
with the same name in the global scope.Consider the following DispatcherServlet
- servlet configuration (in the web.xml file):
+ Servlet configuration (in the web.xml file):
<web-app>
@@ -324,12 +326,12 @@
</web-app>
- With the above servlet configuration in place, you
+ With the above Servlet configuration in place, you
will need to have a file called /WEB-INF/golfing-servlet.xml in your
application; this file will contain all of your Spring Web MVC-specific
components (beans). You can change the exact location of this
- configuration file through a servlet initialization parameter (see below
+ configuration file through a Servlet initialization parameter (see below
for details).
@@ -339,7 +341,7 @@
that has some extra features necessary for web applications. It differs
from a normal ApplicationContext in that it
is capable of resolving themes (see ),
- and that it knows which servlet it is associated with (by having a link to
+ and that it knows which Servlet it is associated with (by having a link to
the ServletContext). The
WebApplicationContext is bound in the
ServletContext, and by using static methods
@@ -451,6 +453,7 @@
in the process to resolve the locale to use when processing the
request (rendering the view, preparing data, and so on). If you do not
need locale resolving, you do not need it.
+
@@ -469,8 +472,8 @@
inspected for multiparts; if multiparts are found, the request is
wrapped in a MultipartHttpServletRequest for
further processing by other elements in the process. See for further information about
- multipart handling.
+ linkend="mvc-multipart" /> for further information about multipart
+ handling.
@@ -509,12 +512,13 @@
client.
You can customize individual
- DispatcherServlet instances by adding servlet
+ DispatcherServlet instances by adding Servlet
initialization parameters (init-param elements) to the
- servlet declaration in the web.xml file. See the
+ Servlet declaration in the web.xml file. See the
following table for the list of supported parameters.
+
@@ -540,7 +544,7 @@
Class that implements
WebApplicationContext, which
- instantiates the context used by this servlet. By default, the
+ instantiates the context used by this Servlet. By default, the
XmlWebApplicationContext is used.
@@ -553,6 +557,7 @@
(using a comma as a delimiter) to support multiple contexts. In
case of multiple context locations with beans that are defined
twice, the latest location takes precedence.
+
@@ -589,10 +594,11 @@
configure access to Servlet or Portlet facilities.
- Available in the samples repository,
- a number of web applications leverage the annotation support described in this section
- including MvcShowcase, MvcAjax,
- MvcBasic, PetClinic,
+ Available in the samples
+ repository, a number of web applications leverage the annotation
+ support described in this section including
+ MvcShowcase, MvcAjax,
+ MvcBasic, PetClinic,
PetCare, and others.
@@ -613,14 +619,14 @@ public class HelloWorldController {
As you can see, the @Controller and
@RequestMapping annotations allow flexible
method names and signatures. In this particular example the method accepts
- a Model and returns a view name as a
- String, but various other method parameters and
- return values can be used as explained later in this section.
- @Controller and
- @RequestMapping and a number of other
- annotations form the basis for the Spring MVC implementation.
- This section documents these annotations and
- how they are most commonly used in a Servlet environment.
+ a Model and returns a view name as a
+ String, but various other method parameters and
+ return values can be used as explained later in this section.
+ @Controller and
+ @RequestMapping and a number of other
+ annotations form the basis for the Spring MVC implementation. This section
+ documents these annotations and how they are most commonly used in a
+ Servlet environment.Defining a controller with
@@ -644,7 +650,9 @@ public class HelloWorldController {
for autodetection, aligned with Spring general support for detecting
component classes in the classpath and auto-registering bean definitions
for them.
+
+
To enable autodetection of such annotated controllers, you add
component scanning to your configuration. Use the
spring-context schema as shown in the following XML
@@ -663,10 +671,9 @@ public class HelloWorldController {
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
- // ...
+ <!-- ... -->
</beans>
-
@@ -681,8 +688,9 @@ public class HelloWorldController {
narrowing the primary mapping for a specific HTTP method request method
("GET", "POST", etc.) or an HTTP request parameter condition.
- The following example from the Petcare sample shows
- a controller in a Spring MVC application that uses this annotation:
+ The following example from the Petcare sample
+ shows a controller in a Spring MVC application that uses this
+ annotation:@Controller
@RequestMapping("/appointments")
@@ -740,9 +748,9 @@ public class AppointmentsController {
A @RequestMapping on the class
level is not required. Without it, all paths are simply absolute, and
- not relative. The following example from the PetClinic sample
- application shows a multi-action controller using
- @RequestMapping:
+ not relative. The following example from the
+ PetClinic sample application shows a multi-action
+ controller using @RequestMapping:
@Controller
public class ClinicController {
@@ -766,80 +774,86 @@ public class ClinicController {
}
- Using @RequestMapping On Interface Methods
-
- A common pitfall when working with annotated controller classes
- happens when applying functionality that requires creating a proxy
- for the controller object (e.g.
- @Transactional methods). Usually you
- will introduce an interface for the controller in order to use JDK
- dynamic proxies. To make this work you must move the
- @RequestMapping annotations to the
- interface as well as the mapping mechanism can only "see" the interface
- exposed by the proxy. Alternatively, you could activate
- proxy-target-class="true" in the configuration for the
- functionality applied to the controller (in our transaction scenario
- in <tx:annotation-driven />). Doing so indicates
- that CGLIB-based subclass proxies should be used instead of
- interface-based JDK proxies. For more information on various proxying
- mechanisms see .
-
-
+ Using @RequestMapping On
+ Interface Methods
+
+ A common pitfall when working with annotated controller classes
+ happens when applying functionality that requires creating a proxy for
+ the controller object (e.g.
+ @Transactional methods). Usually you
+ will introduce an interface for the controller in order to use JDK
+ dynamic proxies. To make this work you must move the
+ @RequestMapping annotations to the
+ interface as well as the mapping mechanism can only "see" the
+ interface exposed by the proxy. Alternatively, you could activate
+ proxy-target-class="true" in the configuration for the
+ functionality applied to the controller (in our transaction scenario
+ in <tx:annotation-driven />). Doing so indicates
+ that CGLIB-based subclass proxies should be used instead of
+ interface-based JDK proxies. For more information on various proxying
+ mechanisms see .
+ URI Template Patterns
- URI templates can be used for convenient access to selected
- parts of a URL in a @RequestMapping method.
-
- A URI Template is a URI-like string, containing one or more
- variable names. When you substitute values for these variables, the
- template becomes a URI. The proposed RFC for URI Templates
- defines how a URI is parameterized. For example, the URI Template
- http://www.example.com/users/{userId} contains the variable
- userId. Assigning the value fred to the variable
- yields http://www.example.com/users/fred.
-
- In Spring MVC you can use the @PathVariable annotation on
- a method argument to bind it to the value of a URI template variable:
+ URI templates can be used for convenient
+ access to selected parts of a URL in a
+ @RequestMapping method.
+
+ A URI Template is a URI-like string, containing one or more
+ variable names. When you substitute values for these variables, the
+ template becomes a URI. The proposed
+ RFC for URI Templates defines how a URI is parameterized. For
+ example, the URI Template
+ http://www.example.com/users/{userId} contains the
+ variable userId. Assigning the value
+ fred to the variable yields
+ http://www.example.com/users/fred.
+
+ In Spring MVC you can use the
+ @PathVariable annotation on a method
+ argument to bind it to the value of a URI template variable:@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
-}
-
+}
The URI Template "/owners/{ownerId}"
specifies the variable name ownerId. When the
- controller handles this request, the value of ownerId
- is set to the value found in the appropriate part of the URI.
- For example, when a request comes in for /owners/fred, the value
- of ownerId is fred.
+ controller handles this request, the value of
+ ownerId is set to the value found in the
+ appropriate part of the URI. For example, when a request comes in for
+ /owners/fred, the value of ownerId is
+ fred.
- To process the @PathVariable annotation, Spring MVC needs to find the
- matching URI template variable by name. You can specify it in the annotation:
+ To process the @PathVariable annotation, Spring MVC needs to
+ find the matching URI template variable by name. You can specify it
+ in the annotation:
- @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
+ @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
// implementation omitted
}
- Or if the URI template variable name matches the method argument name
- you can omit that detail. As long as your code is not compiled without debugging
- information, Spring MVC will match the method argument name to the URI template variable name:
-
- @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
+ Or if the URI template variable name matches the method
+ argument name you can omit that detail. As long as your code is not
+ compiled without debugging information, Spring MVC will match the
+ method argument name to the URI template variable name:
+
+ @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
// implementation omitted
}
-
-
+
- A method can have any number of @PathVariable annotations:
+ A method can have any number of
+ @PathVariable annotations:@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)
public String findPet(@PathVariable String ownerId, @PathVariable String owne
Pet pet = owner.getPet(petId);
model.addAttribute("pet", pet);
return "displayPet";
-}
-
+}
- A URI template can be assembled from type and path level @RequestMapping
- annotations. As a result the findPet() method can be invoked with a URL
+ A URI template can be assembled from type and path level
+ @RequestMapping annotations. As a result the
+ findPet() method can be invoked with a URL
such as /owners/42/pets/21.@Controller
@@ -863,165 +877,174 @@ public class RelativePathUriTemplateController {
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
-}
-
-
- A @PathVariable argument can be of
- any simple type such as int, long, Date, etc.
- Spring automatically converts to the appropriate type or throws a
- TypeMismatchException if it fails to do so.
- You can also register support for parsing additional data types.
- See and .
-
+}
+ A @PathVariable argument can be
+ of any simple type such as int, long,
+ Date, etc. Spring automatically converts to the appropriate type or
+ throws a TypeMismatchException if it fails to
+ do so. You can also register support for parsing additional data
+ types. See and .URI Template Patterns with Regular Expressions
-
- Sometimes you need more precision in defining URI template variables.
- Consider the URL "/spring-web/spring-web-3.0.5.jar".
- How do you break it down into multiple parts?
-
- The @RequestMapping annotation supports the
- use of regular expressions in URI template variables.
- The syntax is {varName:regex} where the first part defines the
- variable name and the second - the regular expression.For example:
+
+ Sometimes you need more precision in defining URI template
+ variables. Consider the URL
+ "/spring-web/spring-web-3.0.5.jar". How do you break it
+ down into multiple parts?
+
+ The @RequestMapping annotation
+ supports the use of regular expressions in URI template variables. The
+ syntax is {varName:regex} where the first part defines
+ the variable name and the second - the regular expression.For
+ example:
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}
-}
-
-
+}
Path Patterns
-
+
In addition to URI templates, the
@RequestMapping annotation also
supports Ant-style path patterns (for example,
/myPath/*.do). A combination of URI templates and
Ant-style globs is also supported (for example,
/owners/*/pets/{petId}).
-
-
+
Consumable Media Types
-
- You can narrow the primary mapping by specifying a list of consumable media types.
- The request will be matched only if the Content-Type request header
- matches the specified media type. For example:
-
+
+ You can narrow the primary mapping by specifying a list of
+ consumable media types. The request will be matched only if the
+ Content-Type request header matches the specified
+ media type. For example:
+
@Controller
-@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
+@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
-}
-
-
- Consumable media type expressions can also be negated as in !text/plain
- to match to all requests other than those with Content-Type of
- text/plain.
-
-
- The consumes condition is supported on the type and on the
- method level. Unlike most other conditions, when used at the type level, method-level
- consumable types override rather than extend type-level consumeable types.
-
-
+}
+
+ Consumable media type expressions can also be negated as in
+ !text/plain to match to all requests other than
+ those with Content-Type of
+ text/plain.
+
+
+ The consumes condition is supported on
+ the type and on the method level. Unlike most other conditions, when
+ used at the type level, method-level consumable types override
+ rather than extend type-level consumeable types.
+ Producible Media Types
-
- You can narrow the primary mapping by specifying a list of producible media types.
- The request will be matched only if the Accept request header
- matches one of these values. Furthermore, use of the produces
- condition ensures the actual content type used to generate the response respects
- the media types specified in the produces condition.
- For example:
-
+
+ You can narrow the primary mapping by specifying a list of
+ producible media types. The request will be matched only if the
+ Accept request header matches one of these
+ values. Furthermore, use of the produces
+ condition ensures the actual content type used to generate the
+ response respects the media types specified in the
+ produces condition. For example:
+
@Controller
-@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
+@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
-}
-
-
- Just like with consumes, producible media type
- expressions can be negated as in !text/plain to match
- to all requests other than those with an Accept header value of
- text/plain.
-
+}
+
+ Just like with consumes, producible media
+ type expressions can be negated as in !text/plain
+ to match to all requests other than those with an
+ Accept header value of
+ text/plain.
+
- The produces condition is supported on the type and on the method level.
- Unlike most other conditions, when used at the type level, method-level producible types
- override rather than extend type-level producible types.
+ The produces condition is supported on
+ the type and on the method level. Unlike most other conditions, when
+ used at the type level, method-level producible types override
+ rather than extend type-level producible types.Request Parameters and Header Values
-
- You can narrow request matching through request parameter conditions such as
- "myParam", "!myParam", or "myParam=myValue".
- The first two test for request parameter presense/absence and the third for a specific parameter value.
- Here is an example with a request parameter value condition:
-
+
+ You can narrow request matching through request parameter
+ conditions such as "myParam", "!myParam", or
+ "myParam=myValue". The first two test for request
+ parameter presense/absence and the third for a specific parameter
+ value. Here is an example with a request parameter value
+ condition:
+
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
- @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
+ @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
-}
-
+}
- The same can be done to test for request header presence/absence or
- to match based on a specific request header value:
+ The same can be done to test for request header presence/absence
+ or to match based on a specific request header value:@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
-@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="myHeader=myValue")
+@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="myHeader=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
-
- Although you can match to Content-Type and
- Accept header values using media type wildcards (for example
- "content-type=text/*" will match to "text/plain"
- and "text/html"), it is recommended to use the
- consumes and produces conditions
- respectively instead. They are intended specifically for that purpose.
-
-
+
+ Although you can match to Content-Type
+ and Accept header values using media type wild
+ cards (for example "content-type=text/*" will
+ match to "text/plain" and
+ "text/html"), it is recommended to use the
+ consumes and produces
+ conditions respectively instead. They are intended specifically for
+ that purpose.
+
- Defining @RequestMapping handler methods
- An @RequestMapping handler method can have a very flexible
- signatures. The supported method arguments and return values are described in the
- following section. Most arguments can be used in arbitrary order with the only
- exception of BindingResult arguments. This is described
- in the next section.
-
+ Defining @RequestMapping handler
+ methods
+
+ An @RequestMapping handler method can have
+ a very flexible signatures. The supported method arguments and return
+ values are described in the following section. Most arguments can be
+ used in arbitrary order with the only exception of
+ BindingResult arguments. This is described in the
+ next section.
+
Supported method argument types
- The following are the supported method arguments:
-
+
+ The following are the supported method arguments: Request or response objects (Servlet API). Choose any
specific request or response type, for example
@@ -1095,31 +1118,32 @@ public class RelativePathUriTemplateController {
- @RequestHeader annotated parameters
- for access to specific Servlet request HTTP headers. Parameter
- values are converted to the declared method argument
+ @RequestHeader annotated
+ parameters for access to specific Servlet request HTTP headers.
+ Parameter values are converted to the declared method argument
type.
- @RequestBody annotated parameters
- for access to the HTTP request body. Parameter values are
- converted to the declared method argument type using
+ @RequestBody annotated
+ parameters for access to the HTTP request body. Parameter values
+ are converted to the declared method argument type using
HttpMessageConverters. See .
- @RequestPart annotated parameters
- for access to the content of a "multipart/form-data" request part.
- See and
- .
+ @RequestPart annotated
+ parameters for access to the content of a "multipart/form-data"
+ request part. See and .
- HttpEntity<?> parameters
- for access to the Servlet request HTTP headers and contents. The request stream will be
- converted to the entity body using
+ HttpEntity<?> parameters for
+ access to the Servlet request HTTP headers and contents. The
+ request stream will be converted to the entity body using
HttpMessageConverters. See .
@@ -1133,15 +1157,14 @@ public class RelativePathUriTemplateController {
-
- org.springframework.web.servlet.mvc.support.RedirectAttributes
- to specify the exact set of attributes to use in case of a redirect
- and also to add flash attributes (attributes stored temporarily on
- the server-side to make them available to the request after the redirect).
- RedirectAttributes is used instead of the implicit
- model if the method returns a "redirect:" prefixed view name or
- RedirectView.
-
+ org.springframework.web.servlet.mvc.support.RedirectAttributes
+ to specify the exact set of attributes to use in case of a
+ redirect and also to add flash attributes (attributes stored
+ temporarily on the server-side to make them available to the
+ request after the redirect).
+ RedirectAttributes is used instead of the
+ implicit model if the method returns a "redirect:" prefixed view
+ name or RedirectView.
@@ -1153,11 +1176,12 @@ public class RelativePathUriTemplateController {
webBindingInitializer property on
RequestMappingHandlerAdapter. Such
command objects along with their validation results will be
- exposed as model attributes by default, using the command class
+ exposed as model attributes by default, using the command class
class name - e.g. model attribute "orderAddress" for a command
- object of type "some.package.OrderAddress".
- The ModelAttribute annotation can be used
- on a method argument to customize the model attribute name used.
+ object of type "some.package.OrderAddress". The
+ ModelAttribute annotation can be used on
+ a method argument to customize the model attribute name
+ used.
@@ -1201,12 +1225,11 @@ public String processSubmit(@ModelAttribute("pet") Pet pet
BindingResult result, Model model) { … }
-
+
Supported method return types
- The following are the supported return types:
-
+ The following are the supported return types: A ModelAndView object, with the
model implicitly enriched with command objects and the results
@@ -1274,10 +1297,9 @@ public String processSubmit(@ModelAttribute("pet") Pet pet
A HttpEntity<?> or
- ResponseEntity<?> object
- to provide access to the Servlet response HTTP headers and
- contents. The entity body will be converted to the response
- stream using
+ ResponseEntity<?> object to provide
+ access to the Servlet response HTTP headers and contents. The
+ entity body will be converted to the response stream using
HttpMessageConverters. See .
@@ -1291,9 +1313,8 @@ public String processSubmit(@ModelAttribute("pet") Pet pet
objects and the results of @ModelAttribute
annotated reference data accessor methods.
-
-
-
+
+ Binding request parameters to method parameters with
@@ -1318,8 +1339,7 @@ public class EditPetForm {
return "petForm";
}
- // ...
-
+ // ...Parameters using this annotation are required by default, but
you can specify that a parameter is optional by setting
@@ -1327,10 +1347,10 @@ public class EditPetForm {
required attribute to false
(e.g., @RequestParam(value="id",
required=false)).
-
- Type conversion is applied automatically if the target method parameter
- type is not String.
- See .
+
+ Type conversion is applied automatically if the target method
+ parameter type is not String. See .
@@ -1350,10 +1370,10 @@ public void handle(@RequestBody String body, Writer writer) throws IOException {
HttpMessageConverter.
HttpMessageConverter is responsible for
converting from the HTTP request message to an object and converting
- from an object to the HTTP response body.
- The RequestMappingHandlerAdapter supports the
- @RequestBody annotation with the following default
- HttpMessageConverters:
+ from an object to the HTTP response body. The
+ RequestMappingHandlerAdapter supports the
+ @RequestBody annotation with the following
+ default HttpMessageConverters:
@@ -1379,16 +1399,16 @@ public void handle(@RequestBody String body, Writer writer) throws IOException {
For more information on these converters, see Message Converters. Also note
- that if using the MVC namespace, a wider range of message converters
- are registered by default. See
- for more information.
+ that if using the MVC namespace, a wider range of message converters
+ are registered by default. See for more information.
- If you intend to read and write XML, you will need to configure the
- MarshallingHttpMessageConverter with a
- specific Marshaller and
- an Unmarshaller implementation from the
- org.springframework.oxm package.
- For example:
+ If you intend to read and write XML, you will need to configure
+ the MarshallingHttpMessageConverter with a
+ specific Marshaller and an
+ Unmarshaller implementation from the
+ org.springframework.oxm package. For
+ example:<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
@@ -1408,34 +1428,36 @@ public void handle(@RequestBody String body, Writer writer) throws IOException {
<property name="unmarshaller" ref="castorMarshaller" />
</bean>
-<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
-
+<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
- An @RequestBody method parameter can be annotated with
- @Valid, in which case it will validated using the configured
- Validator instance. When using the MVC namespace a JSR-303
- validator is configured automatically assuming a JSR-303 implementation is available
- on the classpath. If validation fails a RequestBodyNotValidException
- is raised. The exception is handled by the DefaultHandlerExceptionResolver
- and results in a 400 error sent back to the client along with
- a message containing the validation errors.
+ An @RequestBody method parameter can be
+ annotated with @Valid, in which case it will
+ validated using the configured Validator
+ instance. When using the MVC namespace a JSR-303 validator is
+ configured automatically assuming a JSR-303 implementation is
+ available on the classpath. If validation fails a
+ RequestBodyNotValidException is raised. The
+ exception is handled by the
+ DefaultHandlerExceptionResolver and results in
+ a 400 error sent back to the client along with a
+ message containing the validation errors.
- Also see for information on
- configuring message converters and a validator through the MVC namespace.
+ Also see for
+ information on configuring message converters and a validator
+ through the MVC namespace.
- Mapping the response body with the @ResponseBody
- annotation
+ Mapping the response body with the
+ @ResponseBody annotationThe @ResponseBody annotation is
similar to @RequestBody. This
- annotation can be put on a method and
- indicates that the return type should be written straight to the HTTP
- response body (and not placed in a Model, or interpreted as a view
- name). For example:
+ annotation can be put on a method and indicates that the return type
+ should be written straight to the HTTP response body (and not placed
+ in a Model, or interpreted as a view name). For example:
@RequestMapping(value = "/something", method = RequestMethod.PUT)
@ResponseBody
@@ -1458,10 +1480,11 @@ public String helloWorld() {
The HttpEntity is similar to
@RequestBody and
- @ResponseBody. Besides getting
- access to the request and response body, HttpEntity
- (and the response-specific subclass ResponseEntity)
- also allows access to the request and response headers, like so:
+ @ResponseBody. Besides getting access
+ to the request and response body, HttpEntity
+ (and the response-specific subclass
+ ResponseEntity) also allows access to the
+ request and response headers, like so:
@RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
@@ -1474,33 +1497,38 @@ public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntit
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
- The above example gets the value of the MyRequestHeader request
- header, and reads the body as a byte array. It adds the MyResponseHeader
- to the response, writes Hello World to the response
+ The above example gets the value of the
+ MyRequestHeader request header, and reads the body
+ as a byte array. It adds the MyResponseHeader to
+ the response, writes Hello World to the response
stream, and sets the response status code to 201 (Created).As with @RequestBody and
- @ResponseBody, Spring
- uses HttpMessageConverter to convert
- from and to the request and response streams. For more
- information on these converters, see the previous section and @ResponseBody, Spring uses
+ HttpMessageConverter to convert from
+ and to the request and response streams. For more information on these
+ converters, see the previous section and Message Converters.
- Using @ModelAttribute on a method
-
- The @ModelAttribute annotation can be used on
- methods or on method arguments. This section explains its usage on methods while the
- next section explains its usage on method arguments.
-
- An @ModelAttribute on a method indicates the purpose
- of that method is to add one or more model attributes. Such methods support the same
- argument types as @RequestMapping methods but cannot
- be mapped directly to requests. Instead @ModelAttribute
- methods in a controller are invoked before @RequestMapping
+ Using @ModelAttribute on a
+ method
+
+ The @ModelAttribute annotation
+ can be used on methods or on method arguments. This section explains
+ its usage on methods while the next section explains its usage on
+ method arguments.
+
+ An @ModelAttribute on a method
+ indicates the purpose of that method is to add one or more model
+ attributes. Such methods support the same argument types as
+ @RequestMapping methods but cannot be
+ mapped directly to requests. Instead
+ @ModelAttribute methods in a controller
+ are invoked before @RequestMapping
methods, within the same controller. A couple of examples:
-
+
// Add one attribute
// The return value of the method is added to the model under the name "account"
@@ -1517,87 +1545,105 @@ public Account addAccount(@RequestParam String number) {
public void populateModel(@RequestParam String number, Model model) {
model.addAttribute(accountManager.findAccount(number));
// add more ...
-}
-
-
- @ModelAttribute methods are used to populate
- the model with commonly needed attributes for example to fill a drop-down with
- states or with pet types, or to retrieve a command object like Account in order
- to use it to represent the data on an HTML form. The latter case is further
- discussed in the next section.
-
- Note the two styles of @ModelAttribute methods.
- In the first, the method adds an attribute implicitly
- by returning it. In the second, the method accepts a Model
- and adds any number of model attributes to it.
- You can choose between the two styles depending on your needs.
-
- A controller can have any number of @ModelAttribute
- methods. All such methods are invoked before @RequestMapping
- methods of the same controller.
-
-
- What happens when a model attribute name is not explicitly specified?
- In such cases a default name is assigned to the model attribute based on its type.
- For example if the method returns an object of type Account,
- the default name used is "account". You can change that through
- the value of the @ModelAttribute annotation.
- If adding attributes directly to the Model, use the
- appropriate overloaded addAttribute(..) method - i.e.
- with or without an attribute name.
-
-
- The @ModelAttribute annotation can be used on
- @RequestMapping methods as well. In that case
- the return value of the @RequestMapping method
- is interpreted as a model attribute rather than as a view name.
- The view name is derived from view name conventions instead much like for methods
- returning void — see .
-
+}
+
+ @ModelAttribute methods are used
+ to populate the model with commonly needed attributes for example to
+ fill a drop-down with states or with pet types, or to retrieve a
+ command object like Account in order to use it to represent the data
+ on an HTML form. The latter case is further discussed in the next
+ section.
+
+ Note the two styles of
+ @ModelAttribute methods. In the first,
+ the method adds an attribute implicitly by returning it. In the
+ second, the method accepts a Model and adds any
+ number of model attributes to it. You can choose between the two
+ styles depending on your needs.
+
+ A controller can have any number of
+ @ModelAttribute methods. All such
+ methods are invoked before
+ @RequestMapping methods of the same
+ controller.
+
+
+ What happens when a model attribute name is not explicitly
+ specified? In such cases a default name is assigned to the model
+ attribute based on its type. For example if the method returns an
+ object of type Account, the default name used
+ is "account". You can change that through the value of the
+ @ModelAttribute annotation. If adding
+ attributes directly to the Model, use the
+ appropriate overloaded addAttribute(..) method -
+ i.e., with or without an attribute name.
+
+
+ The @ModelAttribute annotation
+ can be used on @RequestMapping methods
+ as well. In that case the return value of the
+ @RequestMapping method is interpreted
+ as a model attribute rather than as a view name. The view name is
+ derived from view name conventions instead much like for methods
+ returning void — see .
- Using @ModelAttribute on a method argument
-
- As explained in the previous section @ModelAttribute
- can be used on methods or on method arguments. This section explains its usage on
- method arguments.
-
- An @ModelAttribute on a method argument indicates
- the argument should be retrieved from the model. If not present in the model, the argument
- should be instantiated first and then added to the model. Once present in the model, the
- argument's fields should be populated from all request parameters that have matching names.
- This is known as data binding in Spring MVC, a very useful mechanism that saves you from
- having to parse each form field individually.
-
+ Using @ModelAttribute on a
+ method argument
+
+ As explained in the previous section
+ @ModelAttribute can be used on methods
+ or on method arguments. This section explains its usage on method
+ arguments.
+
+ An @ModelAttribute on a method
+ argument indicates the argument should be retrieved from the model. If
+ not present in the model, the argument should be instantiated first
+ and then added to the model. Once present in the model, the argument's
+ fields should be populated from all request parameters that have
+ matching names. This is known as data binding in Spring MVC, a very
+ useful mechanism that saves you from having to parse each form field
+ individually.
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
}
-
- Given the above example where can the Pet instance come from?
- There are several options:
-
+
+ Given the above example where can the Pet instance come from?
+ There are several options:
+
- It may already be in the model due to use of
- @SessionAttributes
- — see .
- It may already be in the model due to an
- @ModelAttribute method in the same
- controller — as explained in the previous section.
- It may be retrieved based on a URI template variable
- and type converter (explained in more detail below).
- It may be instantiated using its default constructor.
+
+ It may already be in the model due to use of
+ @SessionAttributes — see .
+
+
+
+ It may already be in the model due to an
+ @ModelAttribute method in the same
+ controller — as explained in the previous section.
+
+
+
+ It may be retrieved based on a URI template variable and
+ type converter (explained in more detail below).
+
+
+
+ It may be instantiated using its default constructor.
+
-
- An @ModelAttribute method is a common
- way to to retrieve an attribute from the database, which may optionally be
- stored between requests through the use of
- @SessionAttributes.
- In some cases it may be convenient to retrieve the attribute by using
- an URI template variable and a type converter. Here is an example:
+
+ An @ModelAttribute method is a
+ common way to to retrieve an attribute from the database, which may
+ optionally be stored between requests through the use of
+ @SessionAttributes. In some cases it
+ may be convenient to retrieve the attribute by using an URI template
+ variable and a type converter. Here is an example:
@RequestMapping(value="/accounts/{account}", method = RequestMethod.PUT)
@@ -1605,27 +1651,30 @@ public String save(@ModelAttribute("account") Account account) {
}
- In this example the name of the model attribute (i.e. "account")
- matches the name of a URI template variable. If you register
- Converter<String, Account> that can turn the
- String account value into an Account
- instance, then the above example will work without the need for an
- @ModelAttribute method.
-
- The next step is data binding. The WebDataBinder
- class matches request parameter names — including query string parameters and
- form fields — to model attribute fields by name. Matching fields are populated
- after type conversion (from String to the target field type) has been applied
- where necessary.
- Data binding and validation are covered in .
- Customizing the data binding process for a controller level is covered in
- .
-
- As a result of data binding there may be errors such as missing required
- fields or type conversion errors. To check for such errors
- add a BindingResult argument immediately following
- the @ModelAttribute argment:
-
+ In this example the name of the model attribute (i.e. "account")
+ matches the name of a URI template variable. If you register
+ Converter<String, Account> that can turn
+ the String account value into an
+ Account instance, then the above example will
+ work without the need for an
+ @ModelAttribute method.
+
+ The next step is data binding. The
+ WebDataBinder class matches request parameter
+ names — including query string parameters and form fields — to model
+ attribute fields by name. Matching fields are populated after type
+ conversion (from String to the target field type) has been applied
+ where necessary. Data binding and validation are covered in . Customizing the data binding process for a
+ controller level is covered in .
+
+ As a result of data binding there may be errors such as missing
+ required fields or type conversion errors. To check for such errors
+ add a BindingResult argument immediately
+ following the @ModelAttribute
+ argument:
+
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
@@ -1637,15 +1686,18 @@ public String processSubmit(@ModelAttribute("pet") Pet pet
// ...
}
-
- With a BindingResult you can check if errors were found in
- which case it's common to render the same form where the errors
- can be shown with the help of Spring's <errors> form tag.
-
- In addition to data binding you can also invoke validation using your own custom
- validator passing the same BindingResult that was used to record
- data binding errors. That allows for data binding and validation errors to be accumulated
- in one place and subsequently reported back to the user:
+
+ With a BindingResult you can check if
+ errors were found in which case it's common to render the same form
+ where the errors can be shown with the help of Spring's
+ <errors> form tag.
+
+ In addition to data binding you can also invoke validation using
+ your own custom validator passing the same
+ BindingResult that was used to record data
+ binding errors. That allows for data binding and validation errors to
+ be accumulated in one place and subsequently reported back to the
+ user:
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
@@ -1659,9 +1711,9 @@ public String processSubmit(@ModelAttribute("pet") Pet pet
// ...
}
- Or you can have validation invoked automatically by adding the
- JSR-303 @Valid annotation:
-
+ Or you can have validation invoked automatically by adding the
+ JSR-303 @Valid annotation:
+
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) {
@@ -1672,15 +1724,15 @@ public String processSubmit(@Valid @ModelAttribute("pet")
// ...
}
-
- See and
- for details on how to configure and use validation.
-
+ See and for details on how to configure and use
+ validation.
+
- Using @SessionAttributes to store model attributes
- in the HTTP session between requests
+ Using @SessionAttributes to store model
+ attributes in the HTTP session between requestsThe type-level @SessionAttributes
annotation declares session attributes used by a specific handler.
@@ -1700,79 +1752,79 @@ public class EditPetForm {
}
- When using controller interfaces (e.g. for AOP proxying), make sure to
- consistently put all your mapping annotations - such as
- @RequestMapping and
- @SessionAttributes - on the controller
- interface rather than on the implementation class.
-
+ When using controller interfaces (e.g., for AOP proxying),
+ make sure to consistently put all your mapping
+ annotations - such as @RequestMapping
+ and @SessionAttributes - on the
+ controller interface rather than on the
+ implementation class.Specifying redirect and flash attributes
- By default all model attributes are considered to be exposed as
- URI template variables in the redirect URL. Of the remaining attributes
- those that are primitive types or collections/arrays of primitive types
- are automatically appended as query parameters.
-
-
- In annotated controllers however the model may contain
- additional attributes originally added for rendering
- purposes (e.g. drop-down field values).
- To gain precise control over the attributes used in a redirect scenario,
- an @RequestMapping method can declare an
- argument of type RedirectAttributes
- and use it to add attributes for use in RedirectView.
- If the controller method does redirect, the content of
- RedirectAttributes is used.
- Otherwise the content of the default Model
- is used.
-
-
-
- The RequestMappingHandlerAdapter provides a flag
- called "ignoreDefaultModelOnRedirect" that can be
- used to indicate the content of the default Model
- should never be used if a controller method redirects.
- Instead the controller method should declare an attribute of type
- RedirectAttributes or if it doesn't do so
- no attributes should be passed on to RedirectView.
- Both the MVC namespace and the MVC Java config (via
- @EnableWebMvc) automatically set
- this flag to true.
-
-
- The RedirectAttributes interface can
- also be used to add flash attributes. Unlike other redirect attributes,
- which end up in the target redirect URL, flash attributes are saved
- in the HTTP session (and hence do not appear in the URL). The model of
- the controller serving the target redirect URL automatically receives
- these flash attributes after which they are removed from the session.
- See for an overview of the general
- support for flash attributes in Spring MVC.
-
-
+ By default all model attributes are considered to be exposed as
+ URI template variables in the redirect URL. Of the remaining
+ attributes those that are primitive types or collections/arrays of
+ primitive types are automatically appended as query parameters.
+
+ In annotated controllers however the model may contain
+ additional attributes originally added for rendering purposes (e.g.
+ drop-down field values). To gain precise control over the attributes
+ used in a redirect scenario, an
+ @RequestMapping method can declare an
+ argument of type RedirectAttributes and
+ use it to add attributes for use in
+ RedirectView. If the controller method does
+ redirect, the content of
+ RedirectAttributes is used. Otherwise
+ the content of the default Model is
+ used.
+
+ The RequestMappingHandlerAdapter provides
+ a flag called "ignoreDefaultModelOnRedirect" that
+ can be used to indicate the content of the default
+ Model should never be used if a
+ controller method redirects. Instead the controller method should
+ declare an attribute of type
+ RedirectAttributes or if it doesn't do
+ so no attributes should be passed on to
+ RedirectView. Both the MVC namespace and the
+ MVC Java config (via @EnableWebMvc)
+ automatically set this flag to true.
+
+ The RedirectAttributes interface
+ can also be used to add flash attributes. Unlike other redirect
+ attributes, which end up in the target redirect URL, flash attributes
+ are saved in the HTTP session (and hence do not appear in the URL).
+ The model of the controller serving the target redirect URL
+ automatically receives these flash attributes after which they are
+ removed from the session. See
+ for an overview of the general support for flash attributes in Spring
+ MVC.
-
+
- Working with "application/x-www-form-urlencoded" data
-
- The previous sections covered use of @ModelAttribute
- to support form submission requests from browser clients. The same annotation is
- recommended for use with requests from non-browser clients as well. However there is
- one notable difference when it comes to working with HTTP PUT requests.
- Browsers can submit form data via HTTP GET or HTTP POST. Non-browser
- clients can also submit forms via HTTP PUT. This presents a challenge because the Servlet
- specification requires the ServletRequest.getParameter*() family
- of methods to support form field access only for HTTP POST, not for HTTP PUT.
-
-
- To support HTTP PUT requests, the spring-web module provides
- the filter HttpPutFormContentFilter, which can be configured
- in web.xml:
-
+ Working with
+ "application/x-www-form-urlencoded" data
+
+ The previous sections covered use of
+ @ModelAttribute to support form
+ submission requests from browser clients. The same annotation is
+ recommended for use with requests from non-browser clients as well.
+ However there is one notable difference when it comes to working with
+ HTTP PUT requests. Browsers can submit form data via HTTP GET or HTTP
+ POST. Non-browser clients can also submit forms via HTTP PUT. This
+ presents a challenge because the Servlet specification requires the
+ ServletRequest.getParameter*() family of methods to
+ support form field access only for HTTP POST, not for HTTP PUT.
+
+ To support HTTP PUT requests, the spring-web
+ module provides the filter
+ HttpPutFormContentFilter, which can be
+ configured in web.xml:
+
<filter>
<filter-name>httpPutFormFilter</filter-name>
@@ -1787,17 +1839,17 @@ public class EditPetForm {
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-</servlet>
-
-
- The above filter intercepts HTTP PUT requests with content type
- application/x-www-form-urlencoded, reads the form data from the
- body of the request, and wraps the ServletRequest in order
- to make the form data available through the ServletRequest.getParameter*()
- family of methods.
+</servlet>
+
+ The above filter intercepts HTTP PUT requests with content type
+ application/x-www-form-urlencoded, reads the form
+ data from the body of the request, and wraps the
+ ServletRequest in order to make the form data
+ available through the
+ ServletRequest.getParameter*() family of
+ methods.
+
-
-
Mapping cookie values with the @CookieValue annotation
@@ -1820,9 +1872,9 @@ public void displayHeaderInfo(@CookieValue("JSESSIONID")
}
- Type conversion is applied automatically if the target method
- parameter type is not String.
- See .
+ Type conversion is applied automatically if the target method
+ parameter type is not String. See .This annotation is supported for annotated handler methods in
Servlet and Portlet environments.
@@ -1843,8 +1895,7 @@ Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
-Keep-Alive 300
-
+Keep-Alive 300
The following code sample demonstrates how to get the value of
the Accept-Encoding and
@@ -1858,16 +1909,19 @@ public void displayHeaderInfo(@RequestHeader("Accept-Encod
}
- Type conversion is applied automatically if the method parameter
- is not String.
- See .
-
- Built-in support is available for converting a comma-separated
- string into an array/collection of strings or other types known to the
- type conversion system. For example a method parameter annotated with
- @RequestHeader("Accept") may be of type
- String but also String[]
- or List<String>.
+ Type conversion is applied automatically if the method parameter
+ is not String. See .
+
+
+ Built-in support is available for converting a comma-separated
+ string into an array/collection of strings or other types known to
+ the type conversion system. For example a method parameter annotated
+ with @RequestHeader("Accept") may be of type
+ String but also
+ String[] or
+ List<String>.
+ This annotation is supported for annotated handler methods in
Servlet and Portlet environments.
@@ -1875,21 +1929,21 @@ public void displayHeaderInfo(@RequestHeader("Accept-Encod
Method Parameters And Type Conversion
-
- String-based values extracted from the request including
- request parameters, path variables, request headers, and cookie values
- may need to be converted to the target type of the method parameter or
- field (e.g. binding a request parameter to a field in an
- @ModelAttribute parameter) they're bound to.
- If the target type is not String, Spring
- automatically converts to the appropriate type.
- All simple types such as int, long, Date, etc. are
- supported. You can further customize the conversion process
- through a WebDataBinder
- (see ) or by registering
- Formatters with the
- FormattingConversionService
- (see ).
+
+ String-based values extracted from the request including request
+ parameters, path variables, request headers, and cookie values may
+ need to be converted to the target type of the method parameter or
+ field (e.g., binding a request parameter to a field in an
+ @ModelAttribute parameter) they're
+ bound to. If the target type is not String,
+ Spring automatically converts to the appropriate type. All simple
+ types such as int, long, Date, etc. are supported. You can further
+ customize the conversion process through a
+ WebDataBinder (see ) or by registering
+ Formatters with the
+ FormattingConversionService (see ).
@@ -1966,23 +2020,25 @@ public class MyFormController {
<property name="webBindingInitializer">
<bean class="org.springframework.samples.petclinic.web.ClinicBindingInitializer" />
</property>
-</bean>
-
+</bean>
+
- Support for the 'Last-Modified' Response Header To Facilitate Content Caching
-
- An @RequestMapping method may wish
- to support 'Last-Modified' HTTP requests,
- as defined in the contract for the Servlet API's
- getLastModified method, to facilitate content caching.
- This involves calculating a lastModified long
- value for a given request, comparing it against the
- 'If-Modified-Since' request header value, and
- potentially returning a response with status code 304 (Not Modified).
- An annotated controller method can achieve that as follows:
-
+ Support for the 'Last-Modified' Response Header To Facilitate
+ Content Caching
+
+ An @RequestMapping method may
+ wish to support 'Last-Modified' HTTP requests, as
+ defined in the contract for the Servlet API's
+ getLastModified method, to facilitate content
+ caching. This involves calculating a lastModified
+ long value for a given request, comparing it
+ against the 'If-Modified-Since' request header
+ value, and potentially returning a response with status code 304 (Not
+ Modified). An annotated controller method can achieve that as
+ follows:
+
@RequestMapping
public String myHandleMethod(WebRequest webRequest, Model model) {
@@ -1997,37 +2053,37 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
// 3. or otherwise further request processing, actually preparing content
model.addAttribute(...);
return "myViewName";
-}
-
- There are two key elements to note:
- calling request.checkNotModified(lastModified)
- and returning null. The former sets
- the response status to 304 before it returns true.
- The latter, in combination with the former, causes
- Spring MVC to do no further processing of the request.
-
-
+}
+
+ There are two key elements to note: calling
+ request.checkNotModified(lastModified) and returning
+ null. The former sets the response status to 304
+ before it returns true. The latter, in combination
+ with the former, causes Spring MVC to do no further processing of the
+ request.
+
Handler mappings
- In previous versions of Spring, users were required to define one
- or more HandlerMapping beans in the web application
- context to map incoming web requests to appropriate handlers. With the
- introduction of annotated controllers, you generally don't need to do
- that because the RequestMappingHandlerMapping
- automatically looks for @RequestMapping
- annotations on all @Controller beans.
+ In previous versions of Spring, users were required to define one or
+ more HandlerMapping beans in the web
+ application context to map incoming web requests to appropriate handlers.
+ With the introduction of annotated controllers, you generally don't need
+ to do that because the RequestMappingHandlerMapping
+ automatically looks for @RequestMapping
+ annotations on all @Controller beans.
However, do keep in mind that all HandlerMapping
- classes extending from AbstractHandlerMapping
- have the following properties that you can use to customize their behavior:
-
-
+ classes extending from AbstractHandlerMapping have
+ the following properties that you can use to customize their
+ behavior:
+
interceptors
+
List of interceptors to use.
HandlerInterceptors are discussed in
@@ -2037,6 +2093,7 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
defaultHandler
+
Default handler to use, when this handler mapping does not
result in a matching handler.
@@ -2045,6 +2102,7 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
order
+
Based on the value of the order property (see the
org.springframework.core.Ordered interface),
@@ -2055,11 +2113,12 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
alwaysUseFullPath
+
If true , Spring uses the full path within
- the current servlet context to find an appropriate handler. If
+ the current Servlet context to find an appropriate handler. If
false (the default), the path within the current
- servlet mapping is used. For example, if a servlet is mapped using
+ Servlet mapping is used. For example, if a Servlet is mapped using
/testing/* and the
alwaysUseFullPath property is set to true,
/testing/viewPage.html is used, whereas if the
@@ -2070,16 +2129,16 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
urlDecode
+
- Defaults to true, as of Spring 2.5.
- If you prefer to compare encoded paths, set this flag to
+ Defaults to true, as of Spring 2.5. If you
+ prefer to compare encoded paths, set this flag to
false. However, the
HttpServletRequest always exposes the
- servlet path in decoded form. Be aware that the servlet path will
+ Servlet path in decoded form. Be aware that the Servlet path will
not match when compared with encoded paths.
-
The following example shows how to configure an interceptor:
@@ -2104,14 +2163,14 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
Interceptors located in the handler mapping must implement
HandlerInterceptor from the
org.springframework.web.servlet package. This
- interface defines three methods: preHandle(..)
- is called before the actual handler is executed;
- postHandle(..) is called after
+ interface defines three methods: preHandle(..) is
+ called before the actual handler is executed;
+ postHandle(..) is called after
the handler is executed; and afterCompletion(..) is
called after the complete request has finished.
These three methods should provide enough flexibility to do all kinds of
preprocessing and postprocessing.
-
+
The preHandle(..) method returns a boolean
value. You can use this method to break or continue the processing of
the execution chain. When this method returns true,
@@ -2120,11 +2179,12 @@ public String myHandleMethod(WebRequest webRequest, Model model) {
has taken care of requests (and, for example, rendered an appropriate
view) and does not continue executing the other interceptors and the
actual handler in the execution chain.
-
- Interceptors can be configured using the interceptors
- property, which is present on all HandlerMapping classes
- extending from AbstractHandlerMapping.
- This is shown in the example below:
+
+ Interceptors can be configured using the
+ interceptors property, which is present on all
+ HandlerMapping classes extending from
+ AbstractHandlerMapping. This is shown in the
+ example below:<beans>
<bean id="handlerMapping"
@@ -2165,7 +2225,7 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {
Calendar cal = Calendar.getInstance();
int hour = cal.get(HOUR_OF_DAY);
- if (openingTime <= hour && hour < closingTime) {
+ if (openingTime <= hour && hour < closingTime) {
return true;
} else {
response.sendRedirect("http://host.com/outsideOfficeHours.html");
@@ -2181,10 +2241,10 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {
hours.
- When using the RequestMappingHandlerMapping
- the actual handler is an instance of HandlerMethod
- which identifies the specific controller method that will be invoked.
-
+ When using the
+ RequestMappingHandlerMapping the actual handler
+ is an instance of HandlerMethod which
+ identifies the specific controller method that will be invoked.As you can see, the Spring adapter class
@@ -2193,12 +2253,12 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {
interface.
- In the example above, the configured interceptor will apply to all
- requests handled with annotated controller methods. If you want to narrow
- down the URL paths to which an interceptor applies, you can use the MVC
- namespace to do that. See .
-
-
+ In the example above, the configured interceptor will apply to
+ all requests handled with annotated controller methods. If you want to
+ narrow down the URL paths to which an interceptor applies, you can use
+ the MVC namespace to do that. See .
+
@@ -2408,7 +2468,7 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
-<!— in views.xml -->
+<!— in views.xml -->
<beans>
<bean name="report" class="org.springframework.example.ReportExcelView"/>
@@ -2488,39 +2548,36 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {
The RedirectView issues an
HttpServletResponse.sendRedirect() call that
- returns to the client browser as an HTTP redirect.
- By default all model attributes are considered to be exposed as URI
- template variables in the redirect URL. Of the remaining attributes
- those that are primitive types or collections/arrays of primitive types
- are automatically appended as query parameters.
-
-
-
- Appending primitive type attributes as query parameters may be the
- desired result if a model instance was prepared specifically for the
- redirect. However, in annotated controllers the model may contain
- additional attributes added for rendering purposes (e.g. drop-down
- field values). To avoid the possibility of having such attributes
- appear in the URL an annotated controller can declare an
- argument of type RedirectAttributes
- and use it to specify the exact attributes to make available to
+ returns to the client browser as an HTTP redirect. By default all
+ model attributes are considered to be exposed as URI template
+ variables in the redirect URL. Of the remaining attributes those that
+ are primitive types or collections/arrays of primitive types are
+ automatically appended as query parameters.
+
+ Appending primitive type attributes as query parameters may be
+ the desired result if a model instance was prepared specifically for
+ the redirect. However, in annotated controllers the model may contain
+ additional attributes added for rendering purposes (e.g. drop-down
+ field values). To avoid the possibility of having such attributes
+ appear in the URL an annotated controller can declare an argument of
+ type RedirectAttributes and use it to
+ specify the exact attributes to make available to
RedirectView. If the controller method decides
- to redirect, the content of RedirectAttributes
- is used. Otherwise the content of the model is used.
-
-
-
- Note that URI template variables from the present request are automatically
- made available when expanding a redirect URL and do not need to be added
- explicitly neither through Model nor
+ to redirect, the content of
+ RedirectAttributes is used. Otherwise
+ the content of the model is used.
+
+ Note that URI template variables from the present request are
+ automatically made available when expanding a redirect URL and do not
+ need to be added explicitly neither through
+ Model nor
RedirectAttributes. For example:
-
- @RequestMapping(value = "/files/{path}", method = RequestMethod.POST)
+
+ @RequestMapping(value = "/files/{path}", method = RequestMethod.POST)
public String upload(...) {
// ...
return "redirect:files/{path}";
-}
-
+}If you use RedirectView and the view is
created by the controller itself, it is recommended that you configure
@@ -2551,10 +2608,10 @@ public String upload(...) {
The net effect is the same as if the controller had returned a
RedirectView, but now the controller itself can
simply operate in terms of logical view names. A logical view name
- such as redirect:/myapp/some/resource will
- redirect relative to the current servlet context, while a name such as
- redirect:http://myhost.com/some/arbitrary/path
- will redirect to an absolute URL.
+ such as redirect:/myapp/some/resource will redirect
+ relative to the current Servlet context, while a name such as
+ redirect:http://myhost.com/some/arbitrary/path will
+ redirect to an absolute URL.
@@ -2652,7 +2709,7 @@ public String upload(...) {
consulted. This latter option is appropriate for singleton
Views that can render an appropriate
representation of the current resource regardless of the logical view
- name. The Accept header may include wildcards, for
+ name. The Accept header may include wild cards, for
example text/*, in which case a View whose
Content-Type was text/xml is a compatible match.
@@ -2756,70 +2813,65 @@ public class ContentController {
Using flash attributes
- Flash attributes provide a way for one request to store attributes
- intended for use in another. This is most commonly needed when redirecting
- — e.g. the Post/Redirect/Get pattern. Flash attributes are saved temporarily
- before the redirect (typically in the session) to be made available to the
- request after the redirect and removed immediately.
-
-
- Spring MVC has two main abstractions in support of flash attributes.
- FlashMap is used to hold flash attributes while
- FlashMapManager is used to store, retrieve,
- and manage FlashMap instances.
-
-
+ Flash attributes provide a way for one request to store attributes
+ intended for use in another. This is most commonly needed when redirecting
+ — for example, the Post/Redirect/Get pattern. Flash
+ attributes are saved temporarily before the redirect (typically in the
+ session) to be made available to the request after the redirect and
+ removed immediately.
+
+ Spring MVC has two main abstractions in support of flash attributes.
+ FlashMap is used to hold flash attributes while
+ FlashMapManager is used to store, retrieve,
+ and manage FlashMap instances.
+
Flash attribute support is always "on" and does not need to enabled
- explicitly although if not used, it never causes HTTP session creation.
- On each request there is an "input" FlashMap with
- attributes passed from a previous request (if any) and an "output"
- FlashMap with attributes to save for a subsequent
+ explicitly although if not used, it never causes HTTP session creation. On
+ each request there is an "input" FlashMap with
+ attributes passed from a previous request (if any) and an "output"
+ FlashMap with attributes to save for a subsequent
request. Both FlashMap instances are accessible
from anywhere in Spring MVC through static methods in
- RequestContextUtils.
-
-
- Annotated controllers typically do not need to work with
- FlashMap directly. Instead an
- @RequestMapping method can accept an argument
- of type RedirectAttributes and use it to
- add flash attributes for a redirect scenario. Flash attributes added via
- RedirectAttributes are automatically
- propagated to the "output" FlashMap. Similarly after the
- redirect attributes from the "input" FlashMap are
- automatically added to the Model
- of the controller serving the target URL.
-
+ RequestContextUtils.
+
+ Annotated controllers typically do not need to work with
+ FlashMap directly. Instead an
+ @RequestMapping method can accept an
+ argument of type RedirectAttributes and use
+ it to add flash attributes for a redirect scenario. Flash attributes added
+ via RedirectAttributes are automatically
+ propagated to the "output" FlashMap. Similarly after the redirect
+ attributes from the "input" FlashMap are
+ automatically added to the Model of the
+ controller serving the target URL.
- Matching requests to flash attributes
- The concept of flash attributes exists in many other Web frameworks
- and has proven to be exposed sometimes to concurrency issues.
- This is because by definition flash attributes are
- to be stored until the next request. However the very "next"
- request may not be the intended recepient but another
- asynchronous request (e.g. polling or resource requests)
- in which case the flash attributes are removed too early.
-
-
- To reduce the possibility of such issues,
- RedirectView automatically "stamps"
- FlashMap instances with the path and query
- parameters of the target redirect URL. In turn the default
- FlashMapManager matches that information to incoming
- requests when looking up the "input" FlashMap.
-
-
- This does not eliminate the possibility of a concurrency issue
- entirely but nevertheless reducess it greatly with information
- that is already available in the redirect URL.
- Therefore the use of flash attributes is recommended
- mainly for redirect scenarios unless the target URL and/or query
- parameters are known.
+ Matching requests to flash attributes
+
+ The concept of flash attributes exists in many other Web
+ frameworks and has proven to be exposed sometimes to concurrency issues.
+ This is because by definition flash attributes are to be stored until
+ the next request. However the very "next" request may not be the
+ intended recipient but another asynchronous request (e.g. polling or
+ resource requests) in which case the flash attributes are removed too
+ early.
+
+ To reduce the possibility of such issues,
+ RedirectView automatically "stamps"
+ FlashMap instances with the path and query
+ parameters of the target redirect URL. In turn the default
+ FlashMapManager matches that information to
+ incoming requests when looking up the "input"
+ FlashMap.
+
+ This does not eliminate the possibility of a concurrency issue
+ entirely but nevertheless reduces it greatly with information that is
+ already available in the redirect URL. Therefore the use of flash
+ attributes is recommended mainly for redirect scenarios unless the
+ target URL and/or query parameters are known.
-
-
+
Using locales
@@ -3105,7 +3157,7 @@ background=/themes/cool/img/coolBg.jpg
- Spring's multipart (fileupload) support
+ Spring's multipart (file upload) supportIntroduction
@@ -3114,10 +3166,11 @@ background=/themes/cool/img/coolBg.jpg
applications. You enable this multipart support with pluggable
MultipartResolver objects, defined in the
org.springframework.web.multipart package. Spring
- provides one MultipartResolver implementation
- for use with
- Commons FileUpload and another for use
- with Servlet 3.0 multipart request parsing.
+ provides one MultipartResolver
+ implementation for use with Commons
+ FileUpload and another for use with Servlet 3.0
+ multipart request parsing.
By default, Spring does no multipart handling, because some
developers want to handle multiparts themselves. You enable Spring
@@ -3131,8 +3184,8 @@ background=/themes/cool/img/coolBg.jpg
- Using a MultipartResolver
- with Commons FileUpload
+ Using a MultipartResolver with
+ Commons FileUploadThe following example shows how to use the
CommonsMultipartResolver:
@@ -3161,31 +3214,31 @@ background=/themes/cool/img/coolBg.jpg
- Using a MultipartResolver
- with Servlet 3.0
-
- In order to use Servlet 3.0 based multipart parsing,
- you need to mark the DispatcherServlet with a
+ Using a MultipartResolver with
+ Servlet 3.0
+
+ In order to use Servlet 3.0 based multipart parsing, you need to
+ mark the DispatcherServlet with a
"multipart-config" section in
- web.xml, or with a
- javax.servlet.MultipartConfigElement in
- programmatic servlet registration, or in case of a custom servlet class
- possibly with a javax.servlet.annotation.MultipartConfig
- annotation on your servlet class. Configuration settings such as
- maximum sizes or storage locations need to be applied at that
- servlet registration level as Servlet 3.0 does not allow for
- those settings to be done from the MultipartResolver.
-
- Once Servlet 3.0 multipart parsing has been enabled
- in one of the above mentioned ways you can add the
- StandardServletMultipartResolver
- to your Spring configuration:
-
+ web.xml, or with a
+ javax.servlet.MultipartConfigElement in
+ programmatic Servlet registration, or in case of a custom Servlet class
+ possibly with a
+ javax.servlet.annotation.MultipartConfig
+ annotation on your Servlet class. Configuration settings such as maximum
+ sizes or storage locations need to be applied at that Servlet
+ registration level as Servlet 3.0 does not allow for those settings to
+ be done from the MultipartResolver.
+
+ Once Servlet 3.0 multipart parsing has been enabled in one of the
+ above mentioned ways you can add the
+ StandardServletMultipartResolver to your Spring
+ configuration:
+
<bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</bean>
-
-
+ Handling a file upload in a form
@@ -3215,7 +3268,8 @@ background=/themes/cool/img/coolBg.jpg
linkend="mvc-ann-controller">normal annotated
@Controller, except that we use
MultipartHttpServletRequest or
- MultipartFile in the method parameters:
+ MultipartFile in the method parameters:
+
@Controller
public class FileUpoadController {
@@ -3232,16 +3286,18 @@ public class FileUpoadController {
}
}
-}
+}
Note how the @RequestParam method
parameters map to the input elements declared in the form. In this
example, nothing is done with the byte[], but in
practice you can save it in a database, store it on the file system, and
so on.
-
+
When using Servlet 3.0 multipart parsing you can also use
- javax.servlet.http.Part for the method parameter:
+ javax.servlet.http.Part for the method
+ parameter:
+
@Controller
public class FileUpoadController {
@@ -3255,19 +3311,18 @@ public class FileUpoadController {
return "redirect:uploadSuccess";
}
-}
-
+}
-
+
Handling a file upload request from programmatic clients
-
- Multipart requests can also be submitted from non-browser clients in
- a RESTful service scenario. All of the above examples and configuration
- apply here as well. However, unlike browsers that typically submit files
- and simple form fields, a programmatic client can also send more complex
- data of a specific content type — for example a multipart request with
- a file and second part with JSON formatted data:
+
+ Multipart requests can also be submitted from non-browser clients
+ in a RESTful service scenario. All of the above examples and
+ configuration apply here as well. However, unlike browsers that
+ typically submit files and simple form fields, a programmatic client can
+ also send more complex data of a specific content type — for example a
+ multipart request with a file and second part with JSON formatted data:
POST /someUrl
Content-Type: multipart/mixed
@@ -3286,24 +3341,22 @@ Content-Type: text/xml
Content-Transfer-Encoding: 8bit
... File Data ...
-
+
You could access the part named "meta-data" with a
- @RequestParam("meta-data") String metadata
- controller method argument. However, you would probably
- prefer to accept a strongly typed object initialized
- from the JSON formatted data in the body of the request
- part, very similar to the way
- @RequestBody converts
- the body of a non-multipart request to a target object
- with the help of an HttpMessageConverter.
-
- You can use the @RequestPart
+ @RequestParam("meta-data") String
+ metadata controller method argument. However, you would
+ probably prefer to accept a strongly typed object initialized from the
+ JSON formatted data in the body of the request part, very similar to the
+ way @RequestBody converts the body of a
+ non-multipart request to a target object with the help of an
+ HttpMessageConverter.
+
+ You can use the @RequestPart
annotation instead of the @RequestParam
- annotation for this purpose. It allows you to have the
- content of a specific multipart passed through an
- HttpMessageConverter
- taking into consideration the 'Content-Type'
- header of the multipart:
+ annotation for this purpose. It allows you to have the content of a
+ specific multipart passed through an
+ HttpMessageConverter taking into consideration
+ the 'Content-Type' header of the multipart:@RequestMapping(value="/someUrl", method = RequestMethod.POST)
public String onSubmit(@RequestPart("meta-data") MetaData metadata,
@@ -3312,28 +3365,25 @@ public String onSubmit(@RequestPart("meta-data") MetaData
}
- Notice how MultipartFile
- method arguments can be accessed with @RequestParam
- or with @RequestPart interchangeably.
- However, the @RequestPart("meta-data") MetaData
- method argument in this case is read as JSON content
- based on its 'Content-Type'
- header and converted with the help of the
- MappingJacksonHttpMessageConverter.
-
-
+ Notice how MultipartFile method arguments
+ can be accessed with @RequestParam or
+ with @RequestPart interchangeably.
+ However, the @RequestPart("meta-data") MetaData
+ method argument in this case is read as JSON content based on its
+ 'Content-Type' header and converted with the help of
+ the MappingJacksonHttpMessageConverter.
-
Handling exceptions
- HandlerExceptionResolver
+ HandlerExceptionResolver
- Spring HandlerExceptionResolver implementations deal
- with unexpected exceptions that occur during controller execution.
+ Spring HandlerExceptionResolver implementations
+ deal with unexpected exceptions that occur during controller execution.
A HandlerExceptionResolver somewhat resembles the
exception mappings you can define in the web application descriptor
web.xml. However, they provide a more flexible way to
@@ -3341,7 +3391,7 @@ public String onSubmit(@RequestPart("meta-data") MetaData
executing when the exception was thrown. Furthermore, a programmatic way
of handling exceptions gives you more options for responding
appropriately before the request is forwarded to another URL (the same
- end result as when you use the servlet specific exception
+ end result as when you use the Servlet specific exception
mappings).Besides implementing the
@@ -3357,58 +3407,75 @@ public String onSubmit(@RequestPart("meta-data") MetaData
handlers.By default, the DispatcherServlet registers
- the DefaultHandlerExceptionResolver. This resolver
- handles certain standard Spring MVC exceptions by setting a specific
- response status code:
-
+ the DefaultHandlerExceptionResolver. This
+ resolver handles certain standard Spring MVC exceptions by setting a
+ specific response status code:
-
-
- Exception
- HTTP Status Code
-
-
-
-
- ConversionNotSupportedException
- 500 (Internal Server Error)
-
-
- HttpMediaTypeNotAcceptableException
- 406 (Not Acceptable)
-
-
- HttpMediaTypeNotSupportedException
- 415 (Unsupported Media Type)
-
-
- HttpMessageNotReadableException
- 400 (Bad Request)
-
-
- HttpMessageNotWritableException
- 500 (Internal Server Error)
-
-
- HttpRequestMethodNotSupportedException
- 405 (Method Not Allowed)
-
-
- MissingServletRequestParameterException
- 400 (Bad Request)
-
-
- NoSuchRequestHandlingMethodException
- 404 (Not Found)
-
-
- TypeMismatchException
- 400 (Bad Request)
-
-
+
+
+ Exception
+
+ HTTP Status Code
+
+
+
+
+
+ ConversionNotSupportedException
+
+ 500 (Internal Server Error)
+
+
+
+ HttpMediaTypeNotAcceptableException
+
+ 406 (Not Acceptable)
+
+
+
+ HttpMediaTypeNotSupportedException
+
+ 415 (Unsupported Media Type)
+
+
+
+ HttpMessageNotReadableException
+
+ 400 (Bad Request)
+
+
+
+ HttpMessageNotWritableException
+
+ 500 (Internal Server Error)
+
+
+
+ HttpRequestMethodNotSupportedException
+
+ 405 (Method Not Allowed)
+
+
+
+ MissingServletRequestParameterException
+
+ 400 (Bad Request)
+
+
+
+ NoSuchRequestHandlingMethodException
+
+ 404 (Not Found)
+
+
+
+ TypeMismatchException
+
+ 400 (Bad Request)
+
+
-
-
+
@@ -3460,18 +3527,19 @@ public class SimpleController {
Convention over configuration supportFor a lot of projects, sticking to established conventions and
- having reasonable defaults is just what they (the projects) need... this
- theme of convention-over-configuration now has explicit support in Spring
- Web MVC. What this means is that if you establish a set of naming
- conventions and suchlike, you can substantially cut
- down on the amount of configuration that is required to set up handler
- mappings, view resolvers, ModelAndView instances,
- etc. This is a great boon with regards to rapid prototyping, and can also
- lend a degree of (always good-to-have) consistency across a codebase
- should you choose to move forward with it into production.
+ having reasonable defaults is just what they (the projects) need, and
+ Spring Web MVC now has explicit support for convention over
+ configuration. What this means is that if you establish a set
+ of naming conventions and suchlike, you can
+ substantially cut down on the amount of configuration
+ that is required to set up handler mappings, view resolvers,
+ ModelAndView instances, etc. This is a great boon
+ with regards to rapid prototyping, and can also lend a degree of (always
+ good-to-have) consistency across a codebase should you choose to move
+ forward with it into production.
Convention-over-configuration support addresses the three core areas
- of MVC — models, views, and controllers.
+ of MVC: models, views, and controllers.
The Controller
@@ -3494,8 +3562,8 @@ public class SimpleController {
}
}
- Here is a snippet from the attendent Spring Web MVC configuration
- file...
+ Here is a snippet from the corresponding Spring Web MVC
+ configuration file:<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
@@ -3659,12 +3727,13 @@ public class SimpleController {
The strategy for generating a name after adding a
- Set or a List
- is to peek into the collection, take the short class name of the first object
- in the collection, and use that with List appended to the
- name. The same applies to arrays although with arrays it is not necessary to
- peek into the array contents. A few examples will make the semantics of name
- generation for collections clearer:
+ Set or a
+ List is to peek into the collection, take
+ the short class name of the first object in the collection, and use that
+ with List appended to the name. The same applies to
+ arrays although with arrays it is not necessary to peek into the array
+ contents. A few examples will make the semantics of name generation for
+ collections clearer:
@@ -3744,8 +3813,7 @@ public class SimpleController {
<property name="suffix" value=".jsp"/>
</bean>
-</beans>
-
+</beans>
Notice how in the implementation of the
handleRequest(..) method no
@@ -3796,7 +3864,7 @@ public class SimpleController {
content has not changed, the server returns 304: Not
Modified.
- Support for ETags is provided by the servlet filter
+ Support for ETags is provided by the Servlet filter
ShallowEtagHeaderFilter. It is a plain Servlet
Filter, and thus can be used in combination with any web framework. The
ShallowEtagHeaderFilter filter creates so-called
@@ -3824,276 +3892,326 @@ public class SimpleController {
<servlet-name>petclinic</servlet-name>
</filter-mapping>
+
- Configuring Spring MVC
-
- Spring 3 introduces a mvc XML configuration namespace that simplifies the setup of Spring MVC inside your web application.
- Instead of registering low-level beans such as AnnotationMethodHandlerAdapter, you can simply use the namespace and its higher-level constructs.
- This is generally preferred unless you require finer-grained control of the configuration at the bean level.
-
-
- The mvc namespace consists of three tags: mvc:annotation-driven, mvc:interceptors, and mvc:view-controller.
- Each of these tags is documented below and in the XML schema.
-
-
- mvc:annotation-driven
-
- This tag registers the RequestMappingHandlerMapping and RequestMappingHandlerAdapter beans that are required for Spring MVC to dispatch requests to @Controllers.
- The tag configures those two beans with sensible defaults based on what is present in your classpath.
- The defaults are:
-
-
-
- Support for Spring 3's Type ConversionService in addition to JavaBeans PropertyEditors during Data Binding.
- A ConversionService instance produced by the org.springframework.format.support.FormattingConversionServiceFactoryBean is used by default.
- This can be overridden by setting the conversion-service attribute.
-
-
-
-
- Support for formatting Number fields using the @NumberFormat annotation
-
-
-
-
- Support for formatting Date, Calendar, Long, and Joda Time fields using the @DateTimeFormat annotation, if Joda Time 1.3 or higher is present on the classpath.
-
-
-
-
- Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is present on the classpath.
- The validation system can be explicitly configured by setting the validator attribute.
-
-
-
-
- HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values.
-
-
- This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:
-
-
- ByteArrayHttpMessageConverter
- converts byte arrays.
-
-
-
- StringHttpMessageConverter converts
- strings.
-
-
-
- ResourceHttpMessageConverter converts
- to/from org.springframework.core.io.Resource
- for all media types.
-
-
-
- SourceHttpMessageConverter converts
- to/from a javax.xml.transform.Source.
-
-
-
- FormHttpMessageConverter converts
- form data to/from a MultiValueMap<String, String>.
-
-
-
- Jaxb2RootElementHttpMessageConverter
- converts Java objects to/from XML — added if JAXB2 is present
- on the classpath.
-
-
-
-
- MappingJacksonHttpMessageConverter
- converts to/from JSON — added if Jackson is present on the classpath.
-
-
-
-
- AtomFeedHttpMessageConverter
- converts Atom feeds — added if Rome is present on the classpath.
-
-
-
-
- RssChannelHttpMessageConverter
- converts RSS feeds — added if Rome is present on the classpath.
-
-
-
-
-
-
- You can provide your own HttpMessageConverters through the
- mvc:message-converters sub-element of mvc:annotation-driven.
- Message converters you provide will take precedence over the
- ones registered by default.
-
-
-
-
- A typical usage is shown below:
-
-Configuring Spring MVC
+
+ Spring 3 introduces a mvc XML configuration
+ namespace that simplifies the setup of Spring MVC inside your web
+ application. Instead of registering low-level beans such as
+ AnnotationMethodHandlerAdapter, you can simply use the namespace and its
+ higher-level constructs. This is generally preferred unless you require
+ finer-grained control of the configuration at the bean level.
+
+ The mvc namespace consists of three tags: mvc:annotation-driven,
+ mvc:interceptors, and mvc:view-controller. Each of these tags is
+ documented below and in the XML
+ schema.
+
+
+ mvc:annotation-driven
+
+ This tag registers the RequestMappingHandlerMapping and
+ RequestMappingHandlerAdapter beans that are required for Spring MVC to
+ dispatch requests to @Controllers. The tag configures those two beans
+ with sensible defaults based on what is present in your classpath. The
+ defaults are:
+
+ Support for Spring 3's Type ConversionService in addition to
+ JavaBeans PropertyEditors during Data Binding. A ConversionService
+ instance produced by the
+ org.springframework.format.support.FormattingConversionServiceFactoryBean
+ is used by default. This can be overridden by setting the
+ conversion-service attribute.
+
+
+
+ Support for formatting Number
+ fields using the @NumberFormat annotation
+
+
+
+ Support for formatting Date,
+ Calendar, Long, and Joda Time fields using the @DateTimeFormat
+ annotation, if Joda Time 1.3 or higher is present on the
+ classpath.
+
+
+
+ Support for validating @Controller
+ inputs with @Valid, if a JSR-303 Provider is present on the
+ classpath. The validation system can be explicitly configured by
+ setting the validator attribute.
+
+
+
+ HttpMessageConverter support for @RequestBody method
+ parameters and @ResponseBody method return values.
+
+ This is the complete list of HttpMessageConverters set up by
+ mvc:annotation-driven:
+
+ ByteArrayHttpMessageConverter
+ converts byte arrays.
+
+
+
+ StringHttpMessageConverter
+ converts strings.
+
+
+
+ ResourceHttpMessageConverter
+ converts to/from
+ org.springframework.core.io.Resource
+ for all media types.
+
+
+
+ SourceHttpMessageConverter
+ converts to/from a
+ javax.xml.transform.Source.
+
+
+
+ FormHttpMessageConverter
+ converts form data to/from a
+ MultiValueMap<String,
+ String>.
+
+
+
+ Jaxb2RootElementHttpMessageConverter
+ converts Java objects to/from XML — added if JAXB2 is
+ present on the classpath.
+
+
+
+ MappingJacksonHttpMessageConverter
+ converts to/from JSON — added if Jackson is present on the
+ classpath.
+
+
+
+ AtomFeedHttpMessageConverter
+ converts Atom feeds — added if Rome is present on the
+ classpath.
+
+
+
+ RssChannelHttpMessageConverter
+ converts RSS feeds — added if Rome is present on the
+ classpath.
+
+
+
+
+ You can provide your own HttpMessageConverters through the
+ mvc:message-converters sub-element of mvc:annotation-driven.
+ Message converters you provide will take precedence over the
+ ones registered by default.
+
+
+ A typical usage is shown below:
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+ http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
-
-
+ <!-- JSR-303 support will be detected on classpath and enabled automatically -->
+ <mvc:annotation-driven/>
-]]>
-
-
-
-
- mvc:interceptors
-
- This tag allows you to register custom HandlerInterceptors or WebRequestInterceptors that should be applied to all HandlerMapping beans.
- You can also restrict the URL paths that specific interceptors apply to.
-
-
- An example of registering an interceptor applied to all URL paths:
-
-
-
-]]>
-
-
- An example of registering an interceptor limited to a specific URL path:
-
-
-
-
-
-
-]]>
-
-
-
- mvc:view-controller
-
- This tag is a shortcut for defining a ParameterizableViewController that immediately forwards to a view when invoked.
- Use it in static cases when there is no Java Controller logic to execute before the view generates the response.
-
-
- An example of view-controller that forwards to a home page is shown below:
-
- ]]>
-
-
-
- mvc:resources
-
- This tag allows static resource requests following a particular URL pattern to be served by a ResourceHttpRequestHandler from
- any of a list of Resource locations. This provides a convenient way to serve static resources from locations other than the
- web application root, including locations on the classpath. The cache-period property may be used to set far future expiration headers
- (1 year is the recommendation of optimization tools such as Page Speed and YSlow) so that they will be more efficiently utilized by the client. The handler
- also properly evaluates the Last-Modified header (if present) so that a 304 status code will be returned as appropriate, avoiding
- unnecessary overhead for resources that are already cached by the client. For example, to serve resource requests with a URL pattern of
- /resources/** from a public-resources directory within the web application root, the tag would be used as follows:
-
- ]]>
-
-
- To serve these resources with a 1-year future expiration to ensure maximum use of the browser cache and a reduction in HTTP requests made by the browser:
-
- ]]>
-
-
- The mapping attribute must be an Ant pattern that can be used by SimpleUrlHandlerMapping, and the location
- attribute must specify one or more valid resource directory locations. Multiple resource locations may be specified using a comma-separated list of values.
- The locations specified will be checked in the specified order for the presence of the resource for any given request. For example, to enable the serving
- of resources from both the web application root and from a known path of /META-INF/public-web-resources/ in any jar on the classpath, the tag
- would be specified as:
-
- ]]>
-
-
- When serving resources that may change when a new version of the application is deployed, it is recommended that you incorporate a version string into the
- mapping pattern used to request the resources, so that you may force clients to request the newly deployed version of your application's resources. Such a
- version string can be parameterized and accessed using SpEL so that it may be easily managed in a single place when deploying new versions.
-
-
- As an example, let's consider an application that uses a performance-optimized custom build (as recommended) of the Dojo JavaScript library in production, and that the build is generally
- deployed within the web application at a path of /public-resources/dojo/dojo.js. Since different parts of Dojo may be incorporated into the
- custom build for each new version of the application, the client web browsers need to be forced to re-download that custom-built dojo.js resource
- any time a new version of the application is deployed. A simple way to achieve this would be to manage the version of the application in a properties file,
- such as:
-
-
-
-
- and then to make the properties file's values accessible to SpEL as a bean using the util:properties tag:
-
- ]]>
-
-
- With the application version now accessible via SpEL, we can incorporate this into the use of the resources tag:
-
- ]]>
-
-
- and finally, to request the resource with the proper URL, we can take advantage of the Spring JSP tags:
-
-
-
-
-
-
-
-]]>
-
-
-
- mvc:default-servlet-handler
-
- This tag allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container's default Servlet),
- while still allowing static resource requests to be handled by the container's default Servlet. It configures a
- DefaultServletHttpRequestHandler with a URL mapping of "/**" and the lowest priority relative to other URL mappings.
-
-
- This handler will forward all requests to the default Servlet. Therefore it is important that it remains last in the order of all
- other URL HandlerMappings. That will be the case if you use <mvc:annotation-driven> or alternatively if you
- are setting up your own customized HandlerMapping instance be sure to set its order property to a value lower than
- that of the DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.
-
-
- To enable the feature using the default setup, simply include the tag in the form:
-
- ]]>
-
-
- The caveat to overriding the "/" Servlet mapping is that the RequestDispatcher for the default Servlet must be
- retrieved by name rather than by path. The DefaultServletHttpRequestHandler will attempt to auto-detect the default
- Servlet for the container at startup time, using a list of known names for most of the major Servlet containers (including Tomcat,
- Jetty, Glassfish, JBoss, Resin, WebLogic, and WebSphere). If the default Servlet has been custom configured
- with a different name, or if a different Servlet container is being used where the default Servlet name is unknown, then the
- default Servlet's name must be explicitly provided as in the following example:
-
- ]]>
-
-
+</beans>
+
+
+
+ mvc:interceptors
+
+ This tag allows you to register custom HandlerInterceptors or
+ WebRequestInterceptors that should be applied to all HandlerMapping
+ beans. You can also restrict the URL paths that specific interceptors
+ apply to.
+
+ An example of registering an interceptor applied to all URL
+ paths:
+
+
+<mvc:interceptors>
+ <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
+</mvc:interceptors>
+
+ An example of registering an interceptor limited to a specific URL
+ path:
+
+
+<mvc:interceptors>
+ <mvc:interceptor>
+ <mapping path="/secure/*"/>
+ <bean class="org.example.SecurityInterceptor" />
+ </mvc:interceptor>
+</mvc:interceptors>
+
+
+
+ mvc:view-controller
+
+ This tag is a shortcut for defining a
+ ParameterizableViewController that immediately
+ forwards to a view when invoked. Use it in static cases when there is no
+ Java Controller logic to execute before the view generates the
+ response.
+
+ An example of view-controller that forwards to a home page is
+ shown below:
+
+
+<mvc:view-controller path="/" view-name="home"/>
+
+
+
+ mvc:resources
+
+ This tag allows static resource requests following a particular
+ URL pattern to be served by a
+ ResourceHttpRequestHandler from any of a list of
+ Resource locations. This provides a convenient
+ way to serve static resources from locations other than the web
+ application root, including locations on the classpath. The
+ cache-period property may be used to set far future
+ expiration headers (1 year is the recommendation of optimization tools
+ such as Page Speed and YSlow) so that they will be more efficiently
+ utilized by the client. The handler also properly evaluates the
+ Last-Modified header (if present) so that a
+ 304 status code will be returned as appropriate, avoiding
+ unnecessary overhead for resources that are already cached by the
+ client. For example, to serve resource requests with a URL pattern of
+ /resources/** from a public-resources
+ directory within the web application root, the tag would be used as
+ follows:
+
+
+<mvc:resources mapping="/resources/**" location="/public-resources/"/>
+
+ To serve these resources with a 1-year future expiration to ensure
+ maximum use of the browser cache and a reduction in HTTP requests made
+ by the browser:
+
+
+<mvc:resources mapping="/resources/**" location="/public-resources/" cache-period="31556926"/>
+
+ The mapping attribute must be an Ant pattern that can
+ be used by SimpleUrlHandlerMapping, and the
+ location attribute must specify one or more valid resource
+ directory locations. Multiple resource locations may be specified using
+ a comma-separated list of values. The locations specified will be
+ checked in the specified order for the presence of the resource for any
+ given request. For example, to enable the serving of resources from both
+ the web application root and from a known path of
+ /META-INF/public-web-resources/ in any jar on the
+ classpath, the tag would be specified as:
+
+
+<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/public-web-resources/"/>
+
+ When serving resources that may change when a new version of the
+ application is deployed, it is recommended that you incorporate a
+ version string into the mapping pattern used to request the resources,
+ so that you may force clients to request the newly deployed version of
+ your application's resources. Such a version string can be parameterized
+ and accessed using SpEL so that it may be easily managed in a single
+ place when deploying new versions.
+
+ As an example, let's consider an application that uses a
+ performance-optimized custom build (as recommended) of the Dojo
+ JavaScript library in production, and that the build is generally
+ deployed within the web application at a path of
+ /public-resources/dojo/dojo.js. Since different parts of
+ Dojo may be incorporated into the custom build for each new version of
+ the application, the client web browsers need to be forced to
+ re-download that custom-built dojo.js resource any time a
+ new version of the application is deployed. A simple way to achieve this
+ would be to manage the version of the application in a properties file,
+ such as:
+
+
+application.version=1.0.0
+
+ and then to make the properties file's values accessible to SpEL
+ as a bean using the util:properties tag:
+
+
+<util:properties id="applicationProps" location="/WEB-INF/spring/application.properties"/>
+
+ With the application version now accessible via SpEL, we can
+ incorporate this into the use of the resources tag:
+
+
+<mvc:resources mapping="/resources-#{applicationProps['application.version']}/**" location="/public-resources/"/>
+
+ and finally, to request the resource with the proper URL, we can
+ take advantage of the Spring JSP tags:
+
+
+<spring:eval expression="@applicationProps['application.version']" var="applicationVersion"/>
+
+<spring:url value="/resources-{applicationVersion}" var="resourceUrl">
+ <spring:param name="applicationVersion" value="${applicationVersion}"/>
+</spring:url>
+
+<script src="${resourceUrl}/dojo/dojo.js" type="text/javascript"> </script>
+
+
+
+ mvc:default-servlet-handler
+
+ This tag allows for mapping the DispatcherServlet to
+ "/" (thus overriding the mapping of the container's default Servlet),
+ while still allowing static resource requests to be handled by the
+ container's default Servlet. It configures a
+ DefaultServletHttpRequestHandler with a URL mapping of
+ "/**" and the lowest priority relative to other URL mappings.
+
+ This handler will forward all requests to the default Servlet.
+ Therefore it is important that it remains last in the order of all other
+ URL HandlerMappings. That will be the case if you use
+ <mvc:annotation-driven> or alternatively if you are
+ setting up your own customized HandlerMapping instance be
+ sure to set its order property to a value lower than that
+ of the DefaultServletHttpRequestHandler, which is
+ Integer.MAX_VALUE.
+
+ To enable the feature using the default setup, simply include the
+ tag in the form:
+
+
+<mvc:default-servlet-handler/>
+
+ The caveat to overriding the "/" Servlet mapping is that the
+ RequestDispatcher for the default Servlet must be retrieved
+ by name rather than by path. The
+ DefaultServletHttpRequestHandler will attempt to
+ auto-detect the default Servlet for the container at startup time, using
+ a list of known names for most of the major Servlet containers
+ (including Tomcat, Jetty, Glassfish, JBoss, Resin, WebLogic, and
+ WebSphere). If the default Servlet has been custom configured with a
+ different name, or if a different Servlet container is being used where
+ the default Servlet name is unknown, then the default Servlet's name
+ must be explicitly provided as in the following example:
+
+
+<mvc:default-servlet-handler default-servlet-name="myCustomDefaultServlet"/>
+
+
More Spring Web MVC Resources
@@ -4102,10 +4220,10 @@ application.version=1.0.0]]>
-
- There are many excellent articles and tutorials that show how to build web applications with Spring MVC.
- Read them at the Spring Documentation page.
-
+ There are many excellent articles and tutorials that show how to
+ build web applications with Spring MVC. Read them at the Spring
+ Documentation page.