Spring MVC Tutorial: Concepts and Code Examples
Spring MVC Tutorial covers basic concepts of Spring along with code examples of all important concepts of Spring MVC. This tutorial can be a very good starting point for any new learners of Spring MVC.
What is Spring MVC framework?
Spring MVC framework is
Spring: Using dependency injection principle
MVC: using model-view-controller design principle
Framework that provides both building blocks to build applications and few ready components
This framework provides architecture and ready components that can be used to develop presentation tier of an application. It is a light weight framework trying to overcome many limitations of other web tier frameworks like Struts and Webwork. This framework supports request and response communication through HTTP requests. Important aspects of this framework are discussed below.
This framework implements many JEE patterns in addition to well known MVC pattern. Front Controller, Application Controller, Intercepting Filter, View Helper, Composite View etc. patterns can be seen working in Spring MVC architecture. DispatcherServlet is the core component of Spring MVC framework. Dispatcher Servlet receives request from a client and takes it through next steps and Spring framework features. This diagram will give you a broader view of this architecture. This Spring MVC Tutorial explains details of each component below.
The Dispatcher Servlet:
This is the servlet in a Spring MVC application defined in web.xml using <servlet> element. It is integrated with rest of the beans and Spring container through the configuration xml named as <servlet-name>-servlet.xml. DispatcherServlet receives all requests from clients, executes the common part of it, delegates specific implementation to the controllers, receives response in ModelandView form, i.e. data and view format, gets view ready to render, and sends response back. This is responsible for reading all configuration and using the ready components of this framework.
DispatcherServlet delegates the request to the controllers to execute the functionality specific part of it. There are many abstract controllers available in this framework which support specific tasks. Each abstract controller provides a method to be overridden by the controllers.
AbstractController: responsible for providing services applicable to any kind of HTTP request. Configurable attributes available are supportedMethods – GET/POST, requireSession, synchronizeOnSession, cacheSession, useExpiresHeader, useCacheHeader. Override handleRequestInternal(HttpServletRequest, HttpServletResponse) method.
ParameterizableViewController: Specifies view name to return WebApplicationContext.
UrlFilenameViewController: Inspects URL, retrieves file name of the file request and uses that as a view name.
MultiActionController: Handles multiple requests and needs MethodNameResolver or ParameterMethodNameResolver to work with. One method represents one action in this controller.
AbstractCommandController: Populates command object with request parameters available in controller. Offers validation features but does not offer form functionality.
AbstractFormController: Models forms using command objects, validates command object, and makes those available in controller. Just that id does not support the view determination.
SimpleFormController: It does everything that the AbstractFormController does and in addition to that it supports the view identification and redirection.
AbstractWizardController: As name suggests, it is to be used for Wizard kind of screen group, features required in a wizard functionality (validate, process start, process finish, etc.) are supported by this controller.
These are POJOs used to bind the request data and make it available on screen. In Struts action forms, we used to extend the objects from a Struts class, but here we don’t need to do it. This is one of the advantages of Spring, that the data objects are not coupled with the framework. There is difference between the command object and form when these terms are used in Spring MVC documentation. Command object represents a POJO that can be bound with the request data, to get it populated. The term ‘Form’ is used to describe the process of binding attributes of the object with fields of a screen form. Thus, submission, resubmission etc. features are associated with respect to a form.
When a request comes to the DispatcherServlet, you may want to take it through different stages. In this framework, you can configure handlers to do this. There are many handlers available that can be used by providing handler mappings. Since you want to take the request through different process steps, the handler must be able to process the request for a definite task and forward the request to next handler in chain. For this it must also contain the list of handlers applied to this request.
BeanNameUrlHandlerMapping: Extends from AbstractHandlerMapping. Maps incoming HTTP request to the bean names configured in application context i.e. as a bean name, in application context, we give url and the bean is of a controller. Thus the url is mapped to a controller.
<bean name=”/saveCustomer.htm” class=”com.myorg.springmvctutorial.web.controller.SaveCustomerController”/>
SimpleUrlHandlerMapping: Extends from AbstractHandlerMapping. More powerful and supports Ant-style url mapping. This mapping we configure at two places. In web.xml we define the url pattern supported.
In application context xml, we map the urls to controller definitions.
HandlerIntercepter: Implementer of this intercept can implement three methods of this intercepter, one that is called before the actual handler execution, second after the handler execution and last one after the complete request processing. Handlers can be configured using SimpleUrlHandlerMapping configuration in application context.
After completion of request processing by a controller, we need to redirect it to a view. Controller gives a view name and DispatcherServlet maps the view name to an appropriate view based on the configuration provided and redirects/forwards the request to that view. Spring MVC provides following types of view resolvers. We can have multiple view resolvers chained in the configuration files.
AbstractCachingViewResolver: Extending this resolver provides ability to cache the views before actually calling the views.
XMLViewResolver: Takes view configuration in xml format compliant with DTD of Spring’s bean factory. Default configuration is searched in WEB-INF/views.xml.
ResourceBundleViewResolver: Definitions are searched in resource bundle i.e. property files. Default classpath property file is searched with name views.properties.
UrlBasedViewResolver: Straightforward url symbol mapping to view.
InternalResourceViewResolver: Subclass of UrlBasedViewResolver that supports JSTL and Tiles view resolving.
VelocityViewReolver: Subclass of UrlBasedViewResolver used to resolve velocity views.
FreeMarkerViewResolver: Subclass of UrlBasedViewResolver used to resolve FreeMarker views.
Redirect and Forward:
Redirecting can be achieved either by controller returning an instance of RedirectView class of Spring, or by prefixing the return view name by ‘redirect:’. If we prefix by ‘forward:’ then the response will be forwarded.
This is useful for multilingual support. DispatcherServlet calls RequestContext.getLocale() method and retrieves the locale. We can add interceptors and locale resolvers to do this. There are few locale resolvers available in Spring MVC, we can tell from where the locale is retrieved by looking at their name – AcceptHeaderLocaleResolver, CookieLocaleResolver, SessionLocaleResolver. LocaleChangeInterceptor can be configured to trap the locale change. It can be used to set the view language based on the locale.
Theme Based Presentation:
Theme is used in many blogging tools to change the look and feel to give better user experience. This concept is now available in Spring MVC. Static files (e.g. css) and images constitute a theme. We can define a theme using ResourceBundleThemeSource and use theme resolvers from FixedThemeResolver, SessionThemeResolver, and CookieThemeResolver to apply the selected theme.
Spring MVC Multipart Support:
Spring MVC has org.springframework.web.multipart package to support multipart i.e. file upload requests. MultipartResolver implementations can be used to resolve these requests.
This framework allows you to map exceptions to views. Implementations of HandlerExceptionResolver, e.g. SimpleMappingExceptionResolver can be used to map and Exception with a error page.
Spring MVC Tutorial Code Examples:
Following articles will take you through the detail code examples of important Spring MVC Tutorial concepts.