Nice book written by Seth Ladd,Darren Davison,Steven Devijver,Colin Yates.
I skipped 8th Chapter about views as currently i am more interested in jsp only.I have also skipped 11th and 12th chapters as i am not interested in Spring Web Flows.
I wanted to share few important points i found from this book.
1) A layer is a logical abstraction within an application. A tier is best thought of as a physical deployment of the layers. Thinking in layers can help the software developer, while thinking in tiers can assist the system administrator.
2) Spring MVC’s User Interface Layer
Spring MVC does a nice job of isolating the UI concerns into a few key interfaces. The org.springframework.web.servlet.View interface represents a view, or page, of the web application. It is responsible for converting the result of the client requested operation (the response model) into a form viewable by the client.
The View interface is completely generic and has no specific view rendering dependencies.Each view technology will provide an implementation of this interface. Spring MVC natively supports JSP, FreeMarker, Velocity, XSLT, JasperReports, Excel, and PDF.
The org.springframework.web.servlet.ViewResolver provides a helpful layer of indirection.The ViewResolver provides a map between view instances and their logical names. For instance, a JSP page with a filename of /WEB-INF/jsp/onSuccess.jsp can be referred to via the name “success”. This decouples the actual View instance from the code referencing it. It’s even possible to chain multiple ViewResolvers together to further create a flexible configuration.
3) The most basic Controller implementation is an org.springframework.web.servlet.mvc.AbstractController, perfect for read-only pages and simple requests. It provides a simple callback for handling a request, along with facilities such as controlling caching via HTTP headers and enforcing certain HTTP methods. For extremely simple Controllers, you may implement the Controller interface directly, although we don’t recommend it because AbstractController
provides many useful features applicable to all types of web requests.
The AbstractController is well suited for web resources that return dynamic information but don’t respond to input.
4) The DispatcherServlet is the Front Controller of the system, handling all incoming requests and coordinating the different subsystems of Spring MVC. For instance, the DispatcherServlet shuttles the ModelAndView returned by Controllers to the appropriate ViewResolvers.
5) <spring:nestedPath> and <spring:bind> tags. These tags work together to create full paths to properties on the command bean, in order to pull values from the bean and return any validation errors on the field. These tags aren’t required, but are recommended as they provide a standard way to retrieve metadata about a form field and its relationship to a property of the command bean.
The <spring:bind> tag will bring a status variable into scope, which is an object that contains the metadata for a bean property from the command bean. The status.value variable is the current value of the property defined by the path, retrieved from executing the getter method. On initial page views, this won’t render anything, as the command bean has not been populated yet. The status.expression variable is the name of the property itself (minus the name of the command bean).
While it might look like overkill at this point to use the Spring tags, their true benefit appears when validation is enabled and errors are generated. By using the <spring:bind> tag, you can easily retrieve any errors associated with a property or retrieve the current value of the property. When validation fails, and the page is re-rendered, these abilities make it easy to display what the user already entered into the form with the appropriate error messages.
6) During initialization, the DispatcherServlet will look for all implementations by type of HandlerAdapters, HandlerMappings, HandlerExceptionResolvers, and ViewResolvers. However, you may turn off this behavior for all types but HandlerAdapter by setting to false the detectAllHandlerMappings, detectAllHandlerExceptionResolvers, or detectAllViewResolvers properties. To set one or more of these properties, you must use the web.xml where you initially declared the DispatcherServlet.
7) HandlerAdapter
The org.springframework.web.servlet.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.
If our application consists of only Controllers, then you may safely ignore this section. Controllers are supported by default, and no explicit configurations for HandlerAdapters are required. However,this is required if you are interested in integrating a third-party framework into Spring MVC.
8) In Spring MVC there are two high-level types of Controllers: Controllers and ThrowawayControllers. Controllers are (typically) singleton, multithreaded page controllers fully aware of the Servlet API (e.g., HttpServletRequest, HttpServletResponse, and so on). A ThrowawayController is an executable command object (providing an execute() method) that is populated directly with request parameters and has no awareness of the Servlet API. A ThrowawayController is not intended for multithreaded use, but instead for one-off execution (hence its name).
9) The org.springframework.web.servlet.mvc.SimpleFormController is a very powerful Controller responsible for handling the entire life cycle of HTML form interaction. This Controller manages and coordinates viewing the form, through validation, and finally to handling the submission. If your page or resource does not have to handle any form submits, you can move up the class hierarchy to use a simpler controller such as AbstractController.
10) SimpleFormController is great when you need to model a form work flow with one page view and one form submission. There are, however, some situations where you might want one Controller to handle more than one work flow. For instance, you may have a logical group of read-only operations, and subclassing an AbstractController for each operation might be a bit verbose for your application. The MultiActionController provides a way to group multiple actions, or request handlers, together in one controller.
The benefits of the MultiActionController include
• fewer physical controllers, thus fewer classes in the system
• logical grouping of actions in one class
• flexible mapping for action methods.
The disadvantages of MultiActionController include
• form handling work flow isn’t explicit, unlike SimpleFormController
• possibility for large, confusing controllers handling many tasks
• no compile-time checks can be performed due to the use of reflection.
The MultiActionController is similar in nature to Struts’ DispatchAction, only much more flexible.
The MultiActionController has the following capabilities:
• flexible action method mapping, defaulting to URL to method name mapping
• command bean binding
• support for one or more Validators
• per-action “last modified” timestamp control
• exception handling
11) To create a tag file, create a directory named tags inside WEB-INF. Any file you place in here with an extension of .tag will be available to your JSP pages just like any other JSP tag.The advantage here is that you do not need to write a Tag Library Descriptor (TLD), plus these .tag files are recompiled on the fly just like JSP pages, making development much easier.
12) Controllers such as SimpleFormController do not have to be singletons. You may configure any controller type as a prototype if you wish, but ThrowawayController must be a prototype because its design is not thread safe.
13) HandlerInterceptors
The Servlet 2.3 specification introduced the idea of filters, common code that can wrap one or more servlets to provide pre- and post-processing of the request and response. Spring MVC supports an analogous concept with its HandlerInterceptors, which wrap request handlers to provide common functionality. Interceptors handle more life cycle events than a standard filter,but filters are more powerful, in that they may directly manipulate or replace the HttpServletRequest and HttpServletResponse objects.
public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception;
void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception;
void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception;
}
Below table describes Interceptor Life Cycle Points
| Method Name | Description |
|---|---|
| preHandle | Called before the request handler is invoked. If it returns false, the request handler is never invoked, and the rest of the interceptor’s methods are never called. |
| postHandle | Called after the handler finishes but before the view is rendered. Useful for placing common objects into the model. |
| afterCompletion | Called after the view is rendered, even if there was an error in handling the request. Useful for resource cleanup. |
14) Spring Web Flow integrates with Spring MVC, Spring Portlet MVC,
Struts, and JavaServer Faces (JSF). Because Spring Web Flow is very self-contained, the entry points to all these frameworks are consistent, and therefore the cost of integration is minimal.
About the Authors
Seth Ladd
Seth Ladd is a software engineer and professional Spring Framework trainer and mentor specializing in object-oriented and testable web applications. He started his own company building websites at age 17, but now enjoys having a real job. Currently working for Camber Corporation, Seth has built and deployed systems for NEC, Rochester Institute of Technology, Brivo Systems, and National Information Consortium. He has architected and developed enterprise applications in Java and C for both the server and remotely connected embedded devices. He enjoys speaking and teaching, and is a frequent presenter at local Java user groups and at corporate developer conferences. Seth is very thankful for living and working in Kailua, Hawaii, with his wife.
Darren Davison
Darren Davison is a principal consultant for UPCO, specializing in J2EE and open source Java technologies. He has been involved with Spring since the summer of 2003, well before its 1.0 release, and he used the framework to underpin a global intranet site for an investment bank. Darren has previously worked for multinational manufacturing and engineering companies on e-business, infrastructure, and many web-based projects. Away from work, Darren enjoys the never-ending journey of discovery that is GNU/Linux. When not in front of a computer screen, he likes reading and any form of live entertainment.
Steven Devijver
Steven Devijver is an experienced Java developer who started developing J2EE applications in 2000. In 2003 he discovered the Spring Framework, and since then he has been one of its most enthusiastic users. Steven is a senior consultant at Interface21, teaching hundreds of students every year about the Spring Framework.
Colin Yates
Colin Yates is a J2EE principal architect who specializes in web-based development. He has been a freelance consultant for the past three years and has worked in a number of environments, both structured and chaotic. Since graduating with a software engineering degree in 1997, he has held a number of positions, including development lead, principal systems engineer, mentor, and professional trainer. His principal skill set includes mentoring others, architecting complex problems into manageable solutions, and optimizing development processes.
Colin was first introduced to the Spring Framework in January 2003 by his mentors, Peter Den Haan and David Hewitt, and he has never looked back. After a couple of years using the Spring and Hibernate technology stack to good effect, in May 2005 he became one of the early adopters of Spring Web Flow, finally finding the missing item in the web development toolbox. A self-confessed addict of the green bar that comes from following test-driven development and XP, Colin regularly frustrates new team members by introducing a continuous build environment.
When not hanging around the Spring support forums http://forum.springframework.org, Colin can be found out walking with his wife and two dogs, practicing martial arts, attending his local church, or preparing for the arrival of his first child.
Also i have read few more online articles regarding spring mvc.
1) I have first read article on javaBeat site about Spring MVC and i thought it is cool.
2) This IBM web site link for introduction to Spring MVC is also cool.
The Spring framework provides a full-featured MVC module for building Web applications. With Spring's pluggable MVC architecture, you can choose whether you want to use the built-in Spring Web framework or a Web framework such as Struts. The framework is highly configurable through strategy interfaces and accommodates multiple view technologies such as JavaServer Pages (JSP) technology, Velocity, Tiles, iText, and POI. The Spring MVC framework is view agnostic, so does not push you to use only JSP technology. Spring MVC separates the roles of the controller, the model object, the dispatcher, and the handler object, which makes them easier to customize.
Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, and theme resolution as well as support for upload files. The default handler is a very simple Controller interface with just one method, ModelAndView handleRequest(request, response). Spring provides a controller hierarchy that can be subclassed. If your application needs to process user entry forms you might subclass AbstractFormController. If you need to process a multi-page entry into a single form you can subclass AbstractWizardFormController.
3) Spring MVC Step By Step tutorial available at spring official site is also great for beginners.
4) Please now refer to updated version of Spring MVC Step By Step tutorial available at spring official site for latest information.
5) View names are mapped to actual view implementations using ViewResolvers
ViewResolvers are configured in the web-tier ApplicationContext.
6) I refered this article also for more info on Spring MVC.
7) The onBind method is called before any validation occurs for each submit. Keep in mind that even if onBind adds errors to the BindException, the validatePage method will still be called.
8) AbstractWizardFormController are Form controller for typical wizard-style workflows.
In contrast to classic forms, wizards have more than one form view page. Therefore, there are various actions instead of one single submit action:
a) finish: trying to leave the wizard successfully, i.e. performing its final action, and thus needing a valid state;
b) cancel: leaving the wizard without performing its final action, and thus without regard to the validity of its current state;
c) page change: showing another wizard page, e.g. the next or previous one, with regard to "dirty back" and "dirty forward".
d) Parameters indicated with setPassRenderParameters will be present for each page. If there are render parameters you need in renderFinish or renderCancel, then you need to pass those forward from the processFinish or processCancel methods, respectively.
9) I think this article provided in devx site clearly differentiates between different Controllers and gives an use case example for this implementation.
10) I thought even this link is also fine.
Hope you enjoy reading the book and articles.
4 comments:
Good job man, very informative!
Thanks a lot Joy for encouraging comments.
Spring comment not a book comment... SimpleFormController has state in the form of a successView instance variable which has a setter. To my thinking, this makes it not thread safe since multiple threads could call the setSuccessView with different values at different times. Seems dubious to rely on implementers to only invoke the setter in a constructor or via a bean factory. Am I wrong ?
Incredible article .... many thanks !!!
Post a Comment