Day 11-Spring MVC
Day 11-Spring MVC
Training
2016
FOUNDATION TRAINING
Spring MVC
1
Deloitte Training 2016
Spring MVC
Day 12
3
Objectives of Day 12 Deloitte Training 2016
View
Renders the response to the request
6
Spring MVC Components Deloitte Training 2016
DispatcherServlet
Spring’s Front Controller implementation
Controller
User created component for handling requests
Encapsulates navigation logic
Delegates to the service objects for business logic
View
Responsible for rendering output
7
contd.. Deloitte Training 2016
ModelAndView
Created by the Controller
8
MVC and DI Deloitte Training 2016
9
Creating a basic Controller Deloitte Training 2016
Process
Create the Controller class
Implement the Controller interface
10
contd.. Deloitte Training 2016
public class BeerListController implements Controller
{
private SpringCheersService service;
public void setService(SpringCheersService service) {
this.service = service;
}
public ModelAndView handleRequest(HttpServletRequest rq,
HttpServletResponse rs) throws Exception
{
List beers = this.service.findAllBeers();
return new ModelAndView("beerList", "beers", beers);
//View name, Model parameter name, Model parameter
} }
11
contd.. Deloitte Training 2016
Things to do –
Configure the Spring MVC infrastructure –
Once per application
Configure the Controller
Map the Controller to one or more URLs
Create a view
Map the view name to the view
12
Spring MVC Views Deloitte Training 2016
13
contd.. Deloitte Training 2016
View names are mapped to actual view
implementations using ViewResolvers
ViewResolvers are configured in the
web-tier ApplicationContext
Automatically detected by
DispatcherServlet
Can configure multiple, ordered
ViewResolvers
14
contd.. Deloitte Training 2016
• InternalResourceViewResolver
• Uses RequestDispatcher to route requests to internal
• resources such as JSPs
• Model data is placed in request scope for access in the
• view
• • FreeMarkerViewResolver
• Uses FreeMarkerView to render the response using the
• FreeMarker template engine
• • VelocityViewResolver
• Uses VelocityView to render the response using the
• FreeMarker template engine
• • BeanNameViewResolver
• Maps the view name to the name of a bean in the
• ApplicationContext.
• Allows for view instances to be explicitly configured
15
Creating a View with JSP Deloitte Training 2016
16
Configuring a Spring MVC Deloitte Training 2016
Application
• Configure the DispatcherServlet in
• web.xml
• Configure ContextLoaderListener or
• ContextLoaderServlet to load the business
• tier and data tier ApplicationContexts
• Create the web-tier ApplicationContext
• configuration file
• Configure Controllers
• Map URLs to Controllers
• Map logical view names to view
• implementations
17
Configuring DispatcherServlet Deloitte Training 2016
• <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>
18
Configuring Deloitte Training 2016
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>
19
Configuring a Spring MVC Deloitte Training 2016
Application
• Creating the web-tier ApplicationContext
• configuration:
• Naming is important – follows the
• pattern /WEB-INF/<servlet_name>-
• servlet.xml
• DispatcherServlet will automatically load
• this file when setting up its
• ApplicationContext
• In our example this would be /WEBINF/
• springcheers-servlet.xml
20
contd.. Deloitte Training 2016
• <bean id="beerListController"
• class="com.springcheers.web.BeerListController">
• <property name="service" ref="service"/>
• </bean>
21
Mapping URLs to Controllers Deloitte Training 2016
22
Configure a HandlerMapping Deloitte Training 2016
• <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>
23
Configuring the ViewResolver Deloitte Training 2016
• <bean id="viewResolver"
• class=“o.s.w.servlet.view.InternalResourceViewResolver">
• <property name="prefix" value="/WEB-INF/jsp/"/>
• <property name="suffix" value=".jsp"/>
• </bean>
24
Understanding Deloitte Training 2016
MultiActionController
• One controller to handle different tasks
• Multiple handler methods
• • Each method handles a different request
• MethodNameResolver determines method
• • Based on parameter or other criteria
• Can use a delegate to come up with
• ModelAndView
• Good for grouping related tasks into a
• single class
25
Creating a Deloitte Training 2016
MultiActionController
• public 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));
• }
• }
26
Configuring a Deloitte Training 2016
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>
27
Unit Testing a Controller Deloitte Training 2016
28
Unit Testing a Controller Deloitte Training 2016
29
contd.. Deloitte Training 2016
30
Integration Testing Deloitte Training 2016
31
Handling Form Posts with Deloitte Training 2016
SimpleFormController
• Create the custom SimpleFormController
• Create the form view
• Adding data binding logic to the form view
• Add error display logic to the form view
• Create the success view
• Define a command object for the form
• Add on submit logic
• Optionally
• Add validation logic
• Hook in custom data binding logic
32
Request Workflow of Deloitte Training 2016
SimpleFormController
• GET request displays the form
• POST request submits the form
• Both have distinct workflow
• GET does not need validation
• POST does not need form view
• ...
• Implement template methods to
• customize behavior
33
GET request – Form Display Deloitte Training 2016
• formBackingObject()
• Retrieve the command object
• Allows for pre-population of the form
• initBinder()
• Register custom editors
• referenceData()
• Load reference data needed for displaying the form
• showForm()
• Completes ModelAndView and returns
• Command object stored in session if configured
• Renders the actual form
34
POST request – form Deloitte Training 2016
submission
• formBackingObject()
• Retrieve the command object
• • Maybe from session, maybe from database
• initBinder()
• Register custom editors
• Binding of request parameters to form
• onBind()
• Called after bind but before validation
• Allows you to manually bind request parameters to the command
• object before validation
• Validation done using Validators
• onBindAndValidate()
• Called after bind and validate
• Allows you to bind parameters to the command that don’t need
• validation
• If validation fails then add errors to the ModelAndView and show
• the form again
• If validation succeeds call onSubmit() callbacks and show the
• success view
35
Creating the Form View Deloitte Training 2016
• <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>
36
Adding Data Binding to the Deloitte Training 2016
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>
37
Adding Error Handling to the Deloitte Training 2016
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>
• <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>
38
Creating the CustomerForm Deloitte Training 2016
Controller
• 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);
• }
• }
39
Validation Architecture Deloitte Training 2016
40
Creating a Validator Deloitte Training 2016
41
Configuring the CustomerForm Deloitte Training 2016
Controller
• <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>
42
Summary Deloitte Training 2016
43