The framework is designed around a DispatcherServlet that dispatches requests to handlers.
The default handler is a very simple Controller interface, just offering the "ModelAndView handleRequest(request,response)" method.
Spring offers both a traditional Controller implementation (using sub-classes) and an annotation implementation.
Spring Web MVC allows you to use any object as a command or form object.
Spring's data binding is highly flexible.
It treats type mismatches as validation errors that can be evaluated by the application, not as system errors (no need to use String properties).
Spring's view resolution is extremely flexible.
View name resolution is highly configurable, either via bean names, via a properties file, or via your own ViewResolver implementation.
You can integrate the web MVC framework of your choice with Spring easily.
Objectives: 9.5 DispatcherServlet
The Spring framework is request-driven, designed around a
central servlet (Front
Controller design pattern) that dispatches requests to controllers.
It integrated with the Spring IoC container and allows you to use all other Spring features.
Standard J2EE servlet configuration:
Each DispatcherServlet has its own
WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext.
These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory.
The WebApplicationContext is an extension of the plain ApplicationContext.
It is capable of resolving themes.
It knows which servlet it is associated with (by having a link to the ServletContext) and can be retrieved by using static methods on the RequestContextUtils class.
DispatcherServlet has special beans it uses in order to be able to process requests and render the appropriate views:
DispatcherServlet initialization parameters:
|contextClass||Class that implements WebApplicationContext, which will be used to instantiate the context used by this servlet. If this parameter isn't specified, the XmlWebApplicationContext will be used.|
|contextConfigLocation||String which is passed to the context instance (specified by contextClass) to indicate where context(s) can be found. The string is potentially split up into multiple strings (using a comma as a delimiter) to support multiple contexts (in case of multiple context locations, of beans that are defined twice, the latest takes precedence).|
|namespace||the namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet.|
Controllers interpret user input and transform such input into a sensible model which will be represented to the user by the view.
AbstractController provides basic infrastructure support.
|supportedMethods||indicates what methods this controller should accept. Usually this is set to both GET and POST, but you can modify this to reflect the method you want to support. If a request is received with a method that is not supported by the controller, the client will be informed of this (expedited by the throwing of a ServletException).|
|requireSession||indicates whether or not this controller requires a HTTP session to do its work. If a session is not present when such a controller receives a request, the user is informed of this by a ServletException being thrown.|
|synchronizeOnSession||use this if you want handling by this controller to be synchronized on the user's HTTP session.|
|cacheSeconds||when you want a controller to generate a caching directive in the HTTP response, specify a positive integer here. By default the value of this property is set to -1 so no caching directives will be included in the generated response.|
|useExpiresHeader||tweaks your controllers to specify the HTTP 1.0 compatible "Expires" header in the generated response. By default the value of this property is true.|
|useCacheHeader||tweaks your controllers to specify the HTTP 1.1 compatible "Cache-Control" header in the generated response. By default the value of this property is true.|
When using the AbstractController as the baseclass override the handleRequestInternal(HttpServletRequest, HttpServletResponse) method.
ParameterizableViewController - defines a viewName property with both getter and setter methods. It can render a view to users without any processing logic.
UrlFilenameViewController - inspects the URL and retrieves the filename of the file request and uses that as a viewname.
A MultiActionController minimizes the number of controllers by supporting the aggregation of multiple request-handling
methods into one controller.
It is capable of mapping requests to method names and then invoking the correct method to handle a particular request.
Methods must conform to the following signature:
Note: The session must be the third argument, and an object to be bound must always be the final argument.
You may also declare custom methods for handling Exceptions that occur during request handling.
Command controllers provide a way to interact with data objects and dynamically bind parameters from the HttpServletRequest to the data object specified.
Specify command (model) object
Objectives: 9.7 Handler Mappings
A handler is an arbitrary Java object that can handle web requests.
The most typical handler used in Spring MVC for handling web requests is a controller
Using a handler mapping you can map incoming web requests to appropriate handlers.
AbstractHandlerMapping has the following properties
BeanNameUrlHandlerMapping maps incoming HTTP requests to names of beans (in the web application context).
Defaults to BeanNameUrlHandlerMapping if no handler mapping is found in the context.
To handle URL: /editaccount.form
The SimpleUrlHandlerMapping is more powerful.
This mapping is configurable in the application context and has Ant-style path matching capabilities
Interceptors must implement HandlerInterceptor.
Interceptors can be called:
Use HandlerInterceptorAdapter to make implementation easier.
Objectives: 9.7 Handler Mappings
Supports JSPs, JSTL, Velocity, Freemarker, XSLT, Excel, PDF..
ViewResolver provides a mapping between view names and actual views.
The View interface addresses the preparation of the request and hands the request over to one of the view technologies.
|AbstractCachingViewResolver||An abstract view resolver which takes care of caching views.|
configuration file written in XML with the same DTD as Spring's
XML bean factories.
The default configuration file is /WEB-INF/views.xml.
definitions in a ResourceBundle,
specified by the bundle basename.
The default file name is views.properties.
The value of the property [viewname].class is the view class and the value of the property [viewname].url as the view url.
|UrlBasedViewResolver||Direct resolution of symbolic view names to URLs, without an explicit mapping definition.|
|InternalResourceViewResolver||A convenience subclass of UrlBasedViewResolver that supports InternalResourceView (i.e. Servlets and JSPs), and subclasses such as JstlView and TilesView.|
|VelocityViewResolver / FreeMarkerViewResolver||A convenience subclass of UrlBasedViewResolver that supports VelocityView (i.e. Velocity templates) or FreeMarkerView respectively and custom subclasses of them.|
If a specific view resolver does not result in a view, Spring will inspect the context to see if other view resolvers are configured.
If there are additional view resolvers, it will continue to inspect them.
If not, it will throw an Exception.
NOTE: The InternalResourceViewResolver will always return a view, so it must be put at the end of the chain.
Controller to create and return an instance of Spring's RedirectView.
If a view name is returned which has the prefix "redirect:", then UrlBasedViewResolver (and all subclasses) will recognize this as a special indication that a redirect is needed. The rest of the view name will be treated as the redirect URL.
Using the RequestContext.getLocale() method, you can always retrieve the locale that was resolved by the locale resolver.
This locale resolver inspects the accept-language header in the request that was sent by the browser of the
Usually this header field contains the locale of the client's operating system.
This locale resolver inspects a Cookie that might exist on the client, to see if a locale is specified.
The SessionLocaleResolver allows you to retrieve locales from the session that might be associated with the user's request.
You can build in changing of locales using the LocaleChangeInterceptor.
This interceptor needs to be added to one of the handler mappings.
It will detect a parameter in the request and change the locale.
Set up a org.springframework.ui.context.ThemeSource.
Implemented theme resolvers
or use a ThemeChangeInterceptor.
The SimpleMappingExceptionResolver. This resolver enables you to take the class name of any exception that might be thrown and map it to a view name.
Allows rapid prototyping.
Consistency across a codebase.
The ControllerClassNameHandlerMapping class is a HandlerMapping implementation that uses a convention to determine the mapping between request URLs and the Controller instances that are to handle those requests.
Example: WelcomeController maps to the '/welcome*' request URL
Objects can be added to the model without specifying their name.
An x.y.User instance added will have the name 'user'.
An x.y.User array with one or more x.y.User elements added will have the name 'userList'.
(Default) The DefaultRequestToViewNameTranslator maps request URLs to logical view names.
Example: URL of 'http://localhost/registration.html' will result in a logical view name of 'registration'.
Objectives: 9.6 Handlers
Enabled by default if you use DisplatcherServlet.
Add DefaultAnnotationHandlerMapping (class level annotations) and AnnotationMethodHandlerAdapter (method level annotations) to context if you use a custom dispatcher or need to customize the mapping strategy.
The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class.
The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.
Use the following to scan for the annotation:
The @RequestMapping annotation is used to map URLs onto an entire class or a particular handler method.
Handler methods which are annotated with @RequestMapping are allowed to have very flexible signatures.
They may have arguments of the following types, in arbitrary order (except for validation results, which need to follow right after the corresponding command object, if desired):
The following return types are supported for handler methods:
The @RequestParam annotation is used to bind request parameters to a method parameter in your controller.
When placed on a method parameter, @ModelAttribute is used to map a model attribute to the specific, annotated method parameter.
@ModelAttribute is also used at the method level to provide reference data for the model.
The type-level @SessionAttributes annotation declares session attributes used by a specific handler.
To customize request parameter binding with PropertyEditors, etc. via Spring's WebDataBinder, you can either use @InitBinder-annotated methods within your controller or externalize your configuration by providing a custom WebBindingInitializer.
Excluded from Exam
Excluded from Exam
Excluded from Exam
Spring offers support for multi-part forms.