spring mvc 2.1 ppt
DESCRIPTION
This document gives a brief overview of Spring MVC 2.1. This document is very simplifield and very easy to learnTRANSCRIPT
Spring MVC
Spring MVC Outline
Overview of MVC paradigmThe components of Spring MVCMVC and Dependency InjectionImplementing a basic ControllerCreating a simple ViewConfiguring a Spring MVC applicationConfiguring URL mappingsMapping views
Grouping request handling logic with MultiActionControllerHandling form postsAdding validationUsing data bindingAdding error reportingConfiguring form and success views
MVC Overview
MVC = Model-View-ControllerClearly separates business, navigationand presentation logicProven mechanism for building a thin,clean web-tier
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
MVC Components
Three core collaborating componentsController• Handles navigation logic and interacts with theservice tier for business logic
Model• The contract between the Controller and theView• Contains the data needed to render the View• Populated by the Controller
View• Renders the response to the request• Pulls data from the model
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Motivation for MVC
Eases maintenance burdenChanges to business logic are less likely tobreak the presentation logicVice versa
Facilitates multi-disciplined teamdevelopmentDevelopers can focus on creating robustbusiness code without having to worryabout breaking the UIDesigners can focus on building usableand engaging UIs without worrying aboutJava
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Motivation for MVC
Use the best tool for the jobJava is especially suited to creatingbusiness logic codeMarkup or templating languages are moresuited to creating HTML layouts
Ease testabilityBusiness and navigation logic areseparated from presentation logic meaningthey can be tested separatelyPractically: you can test more codeoutside the servlet container
MVC in Spring
A single Front Controller servlet thatdispatches requests to individual ControllersProven pattern shown in Struts and Core J2EEPatterns
Request routing is completely controlled by theFront ControllerIndividual Controllers can be used to handle manydifferent URLs
Controllers are POJOsControllers are managed exactly like any otherbean in the Spring ApplicationContext
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Core Components of Spring MVC
DispatcherServlet
Spring’s Front Controller implementationController
User created component for handlingrequestsEncapsulates navigation logicDelegates to the service objects forbusiness logic
View
Responsible for rendering output
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Core Components of Spring MVC
ModelAndView
Created by the ControllerStores the Model dataAssociates a View to the request• Can be a physical View implementation or alogical View name
ViewResolver
Used to map logical View names to actual Viewimplementations
HandlerMapping
Strategy interface used by DispatcherServletfor mapping incoming requests to individualControllers
MVC and Dependency Injection
All MVC components are configured in theSpring ApplicationContextAs such, all MVC components can beconfigured using Dependency InjectionExample:
<bean id="springCheersController" class="com....web.SpringCheersController"><property name="methodNameResolver“ ref=“springCheersMethodResolver"/><property name="service" ref="service"/></bean>
Creating a Basic Controller
GoalsCreate a thin-wrapper around the businessfunctionalityKeep all business processing out of the web tierHandle only navigation logic
ProcessCreate the Controller class• Implement the Controller interface
• Or extend one of the pre-built Controllerimplementations
Create a setter to inject the service objectImplement the handleRequest() method
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
public class BeerListController implements Controller {private SpringCheersService service;
public void setService(SpringCheersService service) {this.service = service;
}
public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)
throws Exception {List beers = this.service.findAllBeers();return new ModelAndView("beerList", "beers", beers);
}}
Creating a Basic Controller
View name
Model parameter name
Model parameter
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Creating a Basic Controller
What did we do?Create a class that implements theController interface
What’s left?Configure the Spring MVC infrastructure• Once per application
Configure the ControllerMap the Controller to one or more URLsCreate a viewMap the view name to the view
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Views in Spring MVC
Extensive support for many different viewtechnologiesJSP, JSTL, Velocity, FreeMarker,JasperReports, PDF, Excel
Views are represented using logical viewnames which are returned by theControllerCan return an actual View class from theController if needed
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
View Resolution in Spring MVC
View names are mapped to actual viewimplementations using ViewResolvers
ViewResolvers are configured in theweb-tier ApplicationContextAutomatically detected byDispatcherServlet
Can configure multiple, orderedViewResolvers
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
ViewResolver Implementations
• InternalResourceViewResolverUses RequestDispatcher to route requests to internalresources such as JSPsModel data is placed in request scope for access in theview
• FreeMarkerViewResolverUses FreeMarkerView to render the response using theFreeMarker template engine
• VelocityViewResolverUses VelocityView to render the response using theFreeMarker template engine
• BeanNameViewResolverMaps the view name to the name of a bean in theApplicationContext.Allows for view instances to be explicitly configured
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Creating a View with JSP and JSTL
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html><head><title>Beer List</title></head><body><table border="0"><c:forEach items="${beers}" var="beer"><tr><td><c:out value="${beer.id}"/></td><td><c:out value="${beer.brand}"/></td>
</tr></c:forEach></table></body>
</html>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring a Spring MVC Application
Configure the DispatcherServlet inweb.xmlConfigure ContextLoaderListener orContextLoaderServlet to load the businesstier and data tier ApplicationContexts
Create the web-tier ApplicationContextconfiguration fileConfigure ControllersMap URLs to ControllersMap logical view names to viewimplementations
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring a Spring MVC Application
DispatcherServlet(awaiting incoming HttpServletRequests)
WebApplicationContext(containing controllers, view resolvers,
locale resolvers andother web -related beans)
WebApplicationContext(s)
(containing middle-tierservices, datasources,
etcetera)
WebApplicationContext(s)
(containing middle-tierservices, datasources,
etcetera)
WebApplicationContext(s)
(containing middle-tierservices, datasources,
etcetera )
Controllers
ViewResolver
HandlerMappingControllers
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring DispatcherServlet
<servlet><servlet-name>springcheers</servlet-name><servlet-class>
o.s.web.servlet.DispatcherServlet</servlet-class><load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping><servlet-name>springcheers</servlet-name><url-pattern>*.htm</url-pattern>
</servlet-mapping>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring ContextLoaderListener
<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener><listener-class>
o.s.web.context.ContextLoaderListener</listener-class>
</listener>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring a Spring MVCApplicationCreating the web-tier ApplicationContextconfiguration:Naming is important – follows thepattern /WEB-INF/<servlet_name>-servlet.xml
DispatcherServlet will automatically loadthis file when setting up itsApplicationContext
In our example this would be /WEB-INF/springcheers-servlet.xml
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring BeerListController
<bean id="beerListController"class="com.springcheers.web.BeerListController">
<property name="service" ref="service"/></bean>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Mapping URLs to Controllers
Mapping request (URLs) to ControllerControlled by implementations of theHandlerMapping interfaceUseful out-of-the-box implementationsBeanNameUrlHandlerMapping• Uses the Controller bean name as the URLmapping
SimpleUrlHandlerMapping• Define a set of URL pattern to bean mappingsMost out of the box implementationssupport Ant-style path matching
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configure a HandlerMapping
<bean id="urlMapping"class="o.s.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><prop key="/list.htm">springCheersController</prop><prop key="/view.htm">springCheersController</prop><prop key="/edit.htm">customerForm</prop><prop key="/create.htm">customerForm</prop><prop key="/beer/list.htm">beerListController</prop>
</props></property>
</bean>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring the ViewResolver
<bean id="viewResolver"class=“o.s.w.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/><property name="suffix" value=".jsp"/>
</bean>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Understanding MultiActionController
One controller to handle different tasksMultiple handler methods• Each method handles a different request
MethodNameResolver determines method• Based on parameter or other criteria
Can use a delegate to come up withModelAndView
Good for grouping related tasks into asingle class
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Creating a MultiActionControllerpublic class SpringCheersController extends MultiActionController {
private SpringCheersService service;
/** setter ommitted */
public ModelAndView handleCustomerList(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("customerList","customers", this.service.getCustomerList());
}
public ModelAndView handleViewCustomer(HttpServletRequest request, HttpServletResponse response)
throws Exception {long id = RequestUtils.getRequiredLongParameter(request, "customerId");return new ModelAndView("viewCustomer",
"customer", this.service.getCustomer(id));}
}
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring a MultiActionController
<bean id="springCheersController"class="com.springcheers.web.SpringCheersController"><property name="methodNameResolver"
ref="springCheersControllerResolver"/><property name="service" ref="service"/>
</bean>
<bean id="springCheersControllerResolver"class="o.s.w.servlet.mvc.multiaction.PropertiesMethodNameResolver"><property name="mappings"><props><prop key="/list.htm">handleCustomerList</prop><prop key="/view.htm">handleViewCustomer</prop>
</props></property>
</bean>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Unit Testing a Controller
Test with mock request, response andserviceGlass-box testingEnsure that the service is invoked asdesiredFits well with a TDD approach
Test a variety of interactionsController with the request and responseController with the service
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Unit Testing a Controllerprivate SpringCheersController controller;private SpringCheersService service;private MockControl serviceControl;
public void setUp() {this.controller = new SpringCheersController();this.serviceControl =
MockControl.createControl(SpringCheersService.class);this.service =
(SpringCheersService) this.serviceControl.getMock();
this.controller.setService(this.service);}
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Unit Testing a Controller
public void testHandleViewCustomer() throws Exception{MockHttpServletRequest request = new MockHttpServletRequest();MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("customerId", "1");
Customer dummyCustomer = new Customer();this.service.getCustomer(1);this.serviceControl.setReturnValue(dummyCustomer);this.serviceControl.replay();
ModelAndView mv = this.controller.handleViewCustomer(request, response);
assertNotNull("ModelAndView should not be null", mv);assertEquals("Invalid view name", "viewCustomer", mv.getViewName());
Customer customer = (Customer)mv.getModel().get("customer");
assertNotNull("Customer should not be null", customer);assertEquals("Invalid customer returned", dummyCustomer, customer);
}
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Integration Testingpublic class BeerListControllerIntegrationTests
extends AbstractControllerIntegrationTests {private BeerListController beerListController;
public void setBeerListController(BeerListController beerListController) {this.beerListController = beerListController;
}
public void testListBeers() throws Exception {MockHttpServletRequest request = new MockHttpServletRequest();MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mv = this.beerListController.handleRequest(request,response);
assertEquals("Incorrect view name", "beerList", mv.getViewName());
List beers = (List) mv.getModel().get("beers");
assertNotNull("Beer list not in model", beers);
int count = jdbcTemplate.queryForInt("select count(0) from beers");assertEquals("Incorrect number of beers in list", count, beers.size());
}}
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Handling Form Posts withSimpleFormController
Create the custom SimpleFormController
Create the form viewAdding data binding logic to the form viewAdd error display logic to the form viewCreate the success viewDefine a command object for the formAdd on submit logicOptionallyAdd validation logicHook in custom data binding logic
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Request Workflow ofSimpleFormControllerGET request displays the formPOST request submits the formBoth have distinct workflowGET does not need validationPOST does not need form view...
Implement template methods tocustomize behavior
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
GET request – Form Display
formBackingObject()
Retrieve the command objectAllows for pre-population of the form
initBinder()
Register custom editorsreferenceData()
Load reference data needed for displaying the formshowForm()
Completes ModelAndView and returns
Command object stored in session if configuredRenders the actual form
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
POST request – form submission
formBackingObject()Retrieve the command object• Maybe from session, maybe from database
initBinder()Register custom editorsBinding of request parameters to form
onBind()Called after bind but before validationAllows you to manually bind request parameters to the commandobject before validation
Validation done using ValidatorsonBindAndValidate()Called after bind and validateAllows you to bind parameters to the command that don’t needvalidation
If validation fails then add errors to the ModelAndView and showthe form againIf validation succeeds call onSubmit() callbacks and show thesuccess view
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Creating the Form View<html><head><title>Spring Cheers</title></head><body><h1>Update Customer</h1><form name="editCustomer" method="POST"><table border="0"><tr><td>Name: </td><td><input type="text" size="30" name=“command.name”/>
</td></tr><tr><td colspan="2"> </td><td><input type="submit" value="Save"/></td>
</tr></table></form></body><html>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Adding Data Binding to the Form
<spring:bind path="command.name">
<td>
<input type="text" size="30"
name="<c:out value='${status.expression}'/>"
value="<c:out value='${status.displayValue}' />"
/>
</td>
</spring:bind>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Adding Error Handling to theForm<spring:bind path="command.name">
<td><input type="text" size="30"
name="<c:out value='${status.expression}'/>"value="<c:out value='${status.displayValue}' />"
/></td><td><c:if test="${status.error}"><div class="error"><c:forEach items="${status.errorMessages}" var="error"><c:out value="${error}"/>
</c:forEach></div>
</c:if></td>
</spring:bind>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Creating the CustomerFormController
public class CustomerForm extends SimpleFormController {
private SpringCheersService service;
public void setService(SpringCheersService service) {this.service = service;
}
protected Object formBackingObject(HttpServletRequest request)throws Exception {
long id = RequestUtils.getLongParameter(request, "customerId", -1);return (id > 0) ? this.service.getCustomer(id) : new Customer();
}
protected void doSubmitAction(Object customer) throws Exception {this.service.saveCustomer((Customer) customer);
}}
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Validation Architecture
Not tied to the HttpServletRequest
Not tied to the web-tier• Validation of domain objects• Input from remote clients also needs validation• Can easy be tested outside of the container
Implementation independence
Conversion errors are non-fatal
• java.lang.Long property• Typing in nothing (converts to null)• Typing in ‘foo’• No difference with respect to validation!!
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Creating a Validator
public class CustomerValidator implements Validator {
public boolean supports(Class cls) {return (cls == Customer.class);
}
public void validate(Object obj, Errors errors) {Customer customer = (Customer) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name", "required", "required");
}}
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Configuring the CustomerFormController
<bean id="customerForm"class="com.springcheers.web.CustomerForm">
<property name="formView" value="editCustomer"/>
<property name="successView" value="redirect:list.htm"/>
<property name="service" ref="service"/>
<property name="validator" ref="customerValidator"/>
</bean>
Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
Summary
Spring MVC provides a sophisticated MVCimplementationInterface-based for easy testingFully integrated with Spring IOCComprehensive view technologyintegration• JSP & JSTL• Velocity• FreeMarker• PDF• Excel