Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started with Spring’s web application development framework
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2 Topics in this Session Overview of Spring MVC Spring MVC Request Processing Lifecycle Key Spring MVC Artifacts –DispatcherServlet –Handlers –Handler Mappings –Views Quick Start
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3 Topics in this Session Overview of Spring MVC Spring MVC Request Processing Lifecycle Key Spring MVC Artifacts –DispatcherServlet –Handlers –Handler Mappings –Views Quick Start
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4 Spring MVC Overview Spring’s web framework –Optional component built on top of the Spring framework Builds on the Java Servlet API –A parallel Portlet version is also provided Comparable to Struts –A request-driven action framework –Easy for Struts users to adopt while providing a stronger architectural foundation
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5 Spring MVC Architectural Strengths Simple model –Easy to get going –Core architecture has few external dependencies Designed for extension –Smart extension points put you in control –Layered architecture facilitates reuse Strong integration –Integrates popular view and controller technologies Uses Spring itself for configuration –All artifacts are testable and benefit from dependency injection
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6 Spring MVC Integration Supported View Technologies –JSP / JSTL –Apache Velocity –Freemarker –Adobe PDF –Microsoft Excel –Jasper Reports –XML / XSLT
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7 Other Key Features Data Binding Framework Annotation-based Configuration Validation Framework Internationalization Support Tag Library
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8 Topics in this Session Overview of Spring MVC Spring MVC Request Processing Lifecycle Key Spring MVC Artifacts –DispatcherServlet –Handlers –Handler Mappings –Views Quick Start
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9 High-Level Spring MVC Request Processing Lifecycle Dispatcher Servlet Dispatcher Servlet Handler View request dispatch request result view render
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10 Request Processing Sequence Dispatcher Servlet Dispatcher Servlet HandlerMapping Handler View service (request, response) getHandler(request) handleRequest (request, response) result view render(result, response)
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11 Topics in this Session Overview of Spring MVC Spring MVC Request Processing Lifecycle Key Spring MVC Artifacts –DispatcherServlet –Handlers –Handler Mappings –Views Quick Start
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12 Dispatcher Servlet The Heart of Spring MVC A Dispatcher Servlet is a front controller that coordinates the processing of all requests into the web application –Dispatches requests to handlers –Issues appropriate responses to clients Analogous to a Struts Action Servlet –But more powerful and customizable Deployable as a standard Java Servlet
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13 Dispatcher Servlet Configuration Uses Spring for configuration –Has its own Spring ApplicationContext managing web-layer beans you define –Delegates to these beans to carry out request processing Has full access to the “root” application context –Enables web beans to obtain references to application beans through dependency injection
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14 Dispatcher Servlet Usage Considerations DispatcherServlets are coarse-grained –Define one per logical web application –Not one per use case Generic dispatcher infrastructure can be used for several responsibilities –To dispatch requests for HTML content –To dispatch requests to web services
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15 handleRequest (request, response) Request Handlers Incoming requests are dispatched to handlers –There are potentially many handlers per DispatcherServlet The Dispatcher’s HandlerMapping determines the handler of each request Dispatcher Servlet Dispatcher Servlet HandlerMapping Handler getHandler(request)
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16 Most HandlerMapping Rules Are Based On URLs URL patterns can be configured in Java public void login() Or in XML –/login.htm=loginHandler –/editAccount.htm=editAccountHandler –/reward/*/**=rewardHandler
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17 Two Different Styles of Handlers Handlers are annotated Or, implement the Controller public class MyLoginHandler { ModelAndView login(HttpServletRequest request) { } public class MyLoginHandler { ModelAndView login(HttpServletRequest request) { } } public interface Controller { ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception; } public interface Controller { ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception; }
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18 Spring MVC Renders a ModelAndView To render a response to the client, Spring MVC needs a ModelAndView –Selects the view to render the response –Contains the data needed for rendering The Model is the contract between the Controller and the View The same Controller often returns different ModelAndView objects –To render different types of responses for different types of actions
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19 ModelAndView Result Object ModelAndView View Model (a java.util.Map) Model (a java.util.Map) Controller Controller returns
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20 Example Controllers An AccountController that creates, shows, updates, and deletes Accounts in the database A LoginController that logs users in A TopPerformingAccountsController that generates an Excel spreadsheet showing the top 20 accounts
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21 Views A Controller returns a view to render the model –The View generates the HTTP response A Controller may return a concrete View implementation like –new InternalResourceView(“/WEB-INF/reward/list.jsp”) –new RewardListingPdf() Or a view name like “list” –The DispatcherServlet will resolve the name to a View implementation Or null –The DispatcherServlet will select the view for the request
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22 View Resolvers The DispatcherServlet delegates to a ViewResolver to map returned view names to View implementations The default ViewResolver treats the view name as a Web Application-relative file path Override this default by registering a ViewResolver bean with the DispatcherServlet Common view resolver strategies –Internal resource –Bean name
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23 Custom Internal Resource View Resolver Example RewardController handle GET /reward/list rewardList model={rewards} DispatcherServlet Custom InternalResource ViewResolver Custom InternalResource ViewResolver rewardList /WEB-INF/views/rewardList.jsp 12 Logical view name Resolved physical path
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24 Topics in this Session Overview of Spring MVC Spring MVC Request Processing Lifecycle Key Spring MVC Artifacts –DispatcherServlet –Handlers –Handler Mappings –Views Quick Start
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25 Quick Start Steps to developing web application functionality with Spring MVC 1.Deploy a Dispatcher Servlet (one-time only) 2.Implement a Controller 3.Implement the View(s) 4.Register the Controller with the DispatcherServlet 5.Deploy and test Repeat steps 2-5 to develop new functionality
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited Deploy a DispatcherServlet Define inside within web.xml rewardsadmin org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/rewardsadmin-servlet-config.xml rewardsadmin org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/rewardsadmin-servlet-config.xml Contains the Servlet’s configuration
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited Deploy a Dispatcher Servlet (2) Map the Servlet to a URL pattern Will now be able to invoke the Servlet like rewardsadmin /* rewardsadmin /*
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28 Initial Dispatcher Servlet Config <!-- Define your “web beans” here such as your Controllers and their URL mapping configurations Web beans here may reference “application beans” in the “root” web application context --> <!-- Define your “web beans” here such as your Controllers and their URL mapping configurations Web beans here may reference “application beans” in the “root” web application context --> /WEB-INF/rewardsadmin-servlet-config.xml
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29 After DispatcherServlet Deployment Root WebApplicationContext All web beans will have access to application beans Java EE™ Web Application DispatcherServlet ApplicationContext
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited Implement a public class RewardController { private RewardLookupService lookupService; RewardController(RewardLookupService rls) { this.lookupService = rls; public ModelAndView showReward(HttpServletRequest request) { String id = request.getParameter(“id”); Reward reward = lookupService.lookupReward(id); ModelAndView result = new ModelAndView(); result.addObject(“reward”, reward); result.setViewName(“rewardView”); return result; public class RewardController { private RewardLookupService lookupService; RewardController(RewardLookupService rls) { this.lookupService = rls; public ModelAndView showReward(HttpServletRequest request) { String id = request.getParameter(“id”); Reward reward = lookupService.lookupReward(id); ModelAndView result = new ModelAndView(); result.addObject(“reward”, reward); result.setViewName(“rewardView”); return result; } } Selects the “rewardView” to render the “reward” model Depends on application service
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited Implement the Views Your Reward Amount=${reward.amount} Date=${reward.date} Account Number=${reward.account} Merchant Number=${reward.merchant} Your Reward Amount=${reward.amount} Date=${reward.date} Account Number=${reward.account} Merchant Number=${reward.merchant} /WEB-INF/views/rewardView.jsp References result model object by name
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited Register the Controller with the DispatcherServlet /WEB-INF/rewardsadmin-servlet-config.xml
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited Deploy and Test Your Reward Amount = $ Date = 2006/12/29 Account Number = Merchant Number = Your Reward Amount = $ Date = 2006/12/29 Account Number = Merchant Number =
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34 Summary of Request Lifecycle Dispatcher Servlet Dispatcher Servlet HandlerMapping Reward Controller Reward Controller JstlView rewardView.jsp JstlView rewardView.jsp getHandler(request) showReward (request) rewardView model={reward} render(model, response) /reward/show?id=1
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. LAB Spring MVC Essentials