Spring MVC

Principle/Theory of Spring/Spring MVC

A key design principle in Spring Web MVC and in Spring in general is the “Open for extension, closed for modification” principle.

Open-Closed Principle

  • The Open-Closed Principle (OCP), described by Bertrand Meyer in is essentially equivalent to the PV pattern and to information hiding
  • A definition of OCP is: Modules should be both open (for extension; adaptable) and closed (the module is closed to modification in ways that affect clients).
  • OCP and PV (Protected Variations Pattern) are essentially two expressions of the same principle, with different emphasis: protection at variation and evolution points. In OCP, “module” includes all discrete software elements, including methods, classes, subsystems, applications, and so forth.
  • In the context of OCP, the phrase “closed with respect to X” means that clients are not affected if X changes.
  • For example, “the class is closed with respect to instance field definitions” through the mechanism of data encapsulation with private fields and public accessing methods. At the same time, they are open to modifying the definitions of the private data, because outside clients are not directly coupled to the private data.
  • As another example, “the tax calculator adapters are closed with respect to their public interface” through implementing the stable ITaxCalculatorAdapter interface.
  • However, the adapters are open to extension by being privately modified in response to changes in the APIs of the external tax calculators, in ways that do not break their clients.

Features of Spring Web MVC

  • Clear separation of roles.
  • Powerful and straightforward configuration of both framework and application classes as JavaBeans. This configuration capability includes easy referencing across contexts, such as from web controllers to business objects and validators.
  • Adaptability, non-intrusiveness, and flexibility. Define any controller method signature you need, possibly using one of the parameter annotations (such as @RequestParam, @RequestHeader, @PathVariable, and more) for a given scenario.
  • Reusable business code, no need for duplication. Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class.
  • Customizable binding and validation. Type mismatches as application-level validation errors that keep the offending value, localized date and number binding, and so on instead of String-only form objects with manual parsing and conversion to business objects.
  • Customizable handler mapping and view resolution. Handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. Spring is more flexible than web MVC frameworks that mandate a particular technique.
  • Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view technology.
  • Customizable locale, time zone and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, and so on.
  • A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes. The custom tags allow for maximum flexibility in terms of markup code.
  • A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier.
  • Beans whose life-cycle is scoped to the current HTTP request or HTTP Session. This is not a specific feature of Spring MVC itself, but rather of the WebApplicationContext container(s) that Spring MVC uses.

Note:- You cannot add advice to final methods when you use Spring MVC as final methods cannot be advised, as they cannot be overridden.

For example, you cannot add advice to the AbstractController.setSynchronizeOnSession()

Important Bean to remember :-

Special bean types in the WebApplicationContext

Bean type Explanation
HandlerMapping Maps incoming requests to handlers and a list of pre- and post-processors (handler interceptors) based on some criteria the details of which vary by HandlerMapping implementation. The most popular implementation supports annotated controllers but other implementations exists as well.
HandlerAdapter Helps the DispatcherServlet to invoke a handler mapped to a request regardless of the handler is actually invoked. For example, invoking an annotated controller requires resolving various annotations. Thus the main purpose of a HandlerAdapter is to shield the DispatcherServlet from such details.
HandlerExceptionResolver Maps exceptions to views also allowing for more complex exception handling code.
ViewResolver Resolves logical String-based view names to actual View types.
LocaleResolver &LocaleContextResolver Resolves the locale a client is using and possibly their time zone, in order to be able to offer internationalized views
ThemeResolver Resolves themes your web application can use, for example, to offer personalized layouts
MultipartResolver Parses multi-part requests for example to support processing file uploads from HTML forms.
FlashMapManager Stores and retrieves the “input” and the “output” FlashMap that can be used to pass attributes from one request to another, usually across a redirect.


Step to Initialize and Load Spring Container :-

  1. Configure web.xml for Dispatcher Servelet











<servlet-name>easyCaseStudydispatcher </servlet-name>







DispatcherServlet Processing Sequence

  • The WebApplicationContext is searched for and bound in the request as an attribute that the controller and other elements in the process can use. It is bound by default under the key DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.
  • The locale resolver is bound to the request to enable elements 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.
  • The theme resolver is bound to the request to let elements such as views determine which theme to use. If you do not use themes, you can ignore it.
  • If you specify a multipart file resolver, the request is inspected for multiparts; if multiparts are found, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process.
  • An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering.
  • If a model is returned, the view is rendered. If no model is returned, (may be due to a preprocessor or postprocessor intercepting the request, perhaps for security reasons), no view is rendered, because the request could already have been fulfilled.


  1. Initialize Spring Application

public class EasyCaseStudyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {     @Override    protected Class<?>[] getRootConfigClasses() {        // GolfingAppConfig defines beans that would be in root-context.xml        return new Class[] { GolfingAppConfig.class };    }     @Override    protected Class<?>[] getServletConfigClasses() {        // GolfingWebConfig defines beans that would be in golfing-servlet.xml        return new Class[] { GolfingWebConfig.class };    }     @Override    protected String[] getServletMappings() {        return new String[] { “/jsp/*” };    } }


  1. DispatcherServlet initialization parameters
Parameter Explanation
contextClass Class that implements WebApplicationContext, which instantiates the context used by this Servlet. By default, theXmlWebApplicationContext is used.
contextConfigLocation String that is passed to the context instance (specified by contextClass) to indicate where context(s) can be found. The string consists potentially of multiple strings (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.
namespace Namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet.
  1. Implement Controllers



  1. Request Method
Method Scope Semantics
GET collection Retrieve resources.
POST collection Create a new resource
PUT resource Update a resource
PATCH resource Update a resource
DELETE resource Delete a resource
OPTIONS any Return available HTTP methods and other options



The HTTP RFC specifies that PUT must take a full new resource representation as the request entity. This means that if for example only certain attributes are provided, those should be removed (i.e. set to null).

An additional method called PATCH has been proposed recently. The semantics of this call are like PUT in that it updates a resource, but unlike PUT, it applies a delta rather than replacing the entire resource. At the time of writing, PATCH was still a proposed standard waiting final approval.

For simple resource representations, the difference is often not important, and many APIs simply implement PUT as a synonym for PATCH. This usually doesn’t give any problems because it is not very common that you need to set an attribute to null, and if you need to, you can always explicitly include it.

However for more complex representations, especially including lists, it becomes very important to be able to express accurately the changes you want to make. Therefore, it is my recommendation now to both provide PATCH and PUT, and make PATCH do an relative update and have PUT replace the entire resource.

It is important to realize that the request entity to PATCH is of a different content-type than the entity that it is modifying. Instead of being a full resource, it is a resource that describes modifications to be made to a resource. For a JSON data model, which is what this essay is advocating, I believe that there are two sensible ways to define the patch format.

  1. An informal approach where you accept a dict with a partial representation of the object. Only attributes that are present are updated. Attributes that are not present are left alone. This approach is simple, but it has the drawback that if the resource has a complex internal structure e.g. containing a big list of dicts, then that entire list of dicts need to be given in the entity. Effectively PATCH becomes similar to PUT again.
  2. A more formal approach would be to accept a list of modifications. Each modification can be a dict specifying the JSON path of the node to modify, the modification (‘add’, ‘remove’, ‘change’) and the new value.