Using Spring framework for developing webapplications
Spring MVC and it’s working ◦ Configuring the Front Controller ◦ Writing Controllers for handling request ◦ Understanding ModelAndView object HandlerMappings and ViewResolvers Form processing Validation And others…
Spring MVC is like any other MVC implementation from outside but morefine-grained and extensible from within
Spring MVC delegates the responsibility for handling HTTP requests to Controllers. Controllers are much like servlets, mapped to one or more URIs and built to work with HttpServletRequest and HttpServletResponse objects. The Controller API makes no attempt to hide its dependence to the Servlet API, instead fully embracing it and exposing its power.
Controllers are responsible for processing HTTP requests, performing whatever work necessary, composing the response objects, and passing control back to the main request handling work flow. The Controller does not handle view rendering, focusing instead on handling the request and response objects and delegating to the service layer. Front PageView View Controller Controller
Front PageView View Controller Controller WebApplicationContext WebApplicationContext Service LayerThis context contains non-web Componentspecific beans DAO DAO
<listener> <listener-class> o.s.web.context.ContextLoaderListener </listener-class> </listener>ContextLoaderListener provided by Spring will create aWebApplicationContext instance by reading applicationContext.xml file fromthe WEB-INF folder by default
<servlet> <servlet-name>spring</servlet-name> <servlet-class> o.s.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/controller/*</url-pattern> </servlet-mapping>DispatcherServlet is the FrontController in a Spring MVC application.DispatcherServlet will handle incoming request mapped to the given url. Bydefault will read the <servlet-name>-servlet.xml file from WEB-INF folder.
The response from a Controller is rendered for output by an instance of the View class. The Controller does not perform any view rendering, nor is it aware of the view rendering technology used. Spring MVC has excellent support for many different view rendering technologies, including template languages such ◦ JSP and JSTL ◦ Velocity & FreeMarker Other bundled view rendering toolkits include ◦ PDF, Excel ◦ JasperReports
When processing is complete, the Controller is responsible for building up the collection of objects that make up the response (the Model) as well as choosing what page (or View) the user sees next. This combination of Model and View is encapsulated in a class named ModelAndView.
Views are single pages, usually created with a template language such as JSP, Velocity, or FreeMarker. Spring MVC also supports such technologies as PDF, Excel, and JasperReports. View systems can be mixed and matched in an application.
ViewResolvers translate a logical view name into a physical View instance. This class is used to keep the Controllers blissfully unaware of the actual view technology in use. ViewResolvers can be chained together if multiple view strategies are required.
The DispatcherServlet manages the entire processing pipeline of a HTTP request, delegating to a wide array of components to complete the request and generate the response like Controllers and ViewResolvers, file upload handlers and LocaleManagers. The DispatcherServlet is the Front Controller for the application, handling all incoming requests and choosing the right Controller for the job.
Discover the request’s Locale; expose for later usage. If the request is a multipart request, the file upload data is exposed for later processing. Locate which request handler is responsible for this request (e.g., a Controller) Locate any request interceptors for this request. Interceptors are like filters, but customized for Spring MVC
Call preHandle()methods on any interceptors, which may circumvent the normal processing order Invoke the Controller Call postHandle()methods on any interceptors If there is any exception, handle it with a HandlerExceptionResolver
Ifno exceptions were thrown, and the Controller returned a ModelAndView instance, then render the view. When rendering the view, first resolve the view name to a View instance Call afterCompletion()methods on any interceptors
DispatcherServlet internally depends on the following components: ◦ LocaleAware ◦ MultipartResolver ◦ HandlerAdapter ◦ HandlerMapping ◦ HandlerInterceptor ◦ HandlerExceptionResolver ◦ ViewResolver
Interface Name Default Bean Name Purpose HandlerMapping handlerMapping Maps request to Controller HandlerAdapter none Decouples handlers from DispatcherServlet ViewResolver viewResolver Maps view names to view instances HandlerExceptionResolver handlerExceptionResolver Maps exceptions to handlers and views MultipartResolver multipartResolver For file uploads LocaleResolver localeResolver For resolving locale of a request ThemeResolver themeResolver For resolving theme for a requestDuring initialization, the DispatcherServlet will look for all implementations by typeof HandlerAdapters, HandlerMappings, HandlerExceptionResolvers, and ViewResolvers.
If you do disable the automatic discovery, you will then need to name at least onebean of each type with the default bean name.Similarly other options are: detectAllHandlerMappings anddetectAllHandlerExceptionResolvers
Interface Name Default Bean Name Implementation ClassHandlerMapping handlerMapping BeanNameUrlHandlerMappingHandlerAdapter none SimpleControllerHandlerAdapterViewResolver viewResolver InternalResourceViewResolverLocaleResolver localeResolver AcceptHeaderLocaleResolverThemeResolver themeResolver FixedThemeResolver There is no default implementation for MultipartResolver, HandlerExceptionResolver or ViewResolver.
HandlerAdapter is a system level interface, allowing for low coupling between different request handlers and the DispatcherServlet. Using this interface, the DispatcherServlet can interact with any type of request handler, as long as a HandlerAdapter is configured. No configuration is needed if request handlers will be Controllers.
The default strategy for mapping requests to handlers is theBeanNameUrlHandlerMapping class. This class treats any bean with a name oralias that starts with the / character as a potential request handler.The bean name, or alias, is then matched against incoming request URLs using Ant-style path matching.
In this approach, bean names are decoupled from url-patterns. Recommended inmost cases over BeanNameUrlHandlerMapping.
Once the Controller has completed the task, it’s the role of ViewResolver tolocate the correct view which will be then rendered back to the client.A view can be a JSP, PDF, Excel sheet, or anything else.
We need to configure ExceptionResolvers manually.SimpleMappingExceptionResolver is a readymade implementation ofHandlerExceptionResolver interface
AcceptHeaderLocaleResolver, FixedLocaleResolver,SessionLocaleResolver and CookieLocaleResolver are the readyimplementations available for this interface
CommonsMultipartResolver is one of the default implementations available
If case if you are aware of AOP interceptors, HandlerInterceptor allows code tobe executed around Controllers without any AOP knowledge plus we getaccess to underlying Servlet API in HandlerInterceptor as compared to generalAOP interceptors.