0% found this document useful (0 votes)
13 views43 pages

Day 11-Spring MVC

Spring MVC

Uploaded by

77rccbgkqb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views43 pages

Day 11-Spring MVC

Spring MVC

Uploaded by

77rccbgkqb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Deloitte

Training
2016

FOUNDATION TRAINING
Spring MVC
1
Deloitte Training 2016

Spring MVC
Day 12

3
Objectives of Day 12 Deloitte Training 2016

 At the end of this module, you will be able to:


 Program a module with MVC paradigm
 Implementing a basic Controller
 Creating a simple View
 Configuring a Spring MVC application
 Configuring URL mappings
 Mapping views
 Grouping request handling logic with MultiActionController
 Handling form posts
 Adding validation
 Using data binding
 Adding error reporting
 Configuring form and success views
4
MVC Overview Deloitte Training 2016
 MVC = Model-View-Controller
 Clearly separates business, navigation and presentation logic
 Proven mechanism for building a thin, clean web-tier.
 Three core collaborating components
 Controller
 Handles navigation logic and interacts with the service tier
for business logic
 Model
 The contract between the Controller and the View

 Contains the data needed to render the View

 Populated by the Controller

 View
 Renders the response to the request

5  Pulls data from the model


Spring MVC Deloitte Training 2016

 A single Front Controller servlet that dispatches requests to


individual Controllers
 Proven pattern shown in Struts and Core J2EE Patterns
 Request routing is completely controlled by the Front Controller
 Individual Controllers can be used to handle many different
URLs
 Controllers are POJOs
 Controllers are managed exactly like any other bean in the
Spring ApplicationContext

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

 Stores the Model data

 Associates a View to the request


o Can be a physical View implementation or a logical View name
 ViewResolver
 Used to map logical View names to actual View
implementations
 HandlerMapping
 Strategy interface used by DispatcherServlet for mapping
incoming requests to individual Controllers.

8
MVC and DI Deloitte Training 2016

 All MVC components are configured in the


Spring ApplicationContext
 As such, all MVC components can be configured using
Dependency Injection
 Example:
<bean id="springCheersController"
class="com....web.SpringCheersController">
<property name="methodNameResolver“
ref=“springCheersMethodResolver"/>
<property name="service" ref="service"/>
</bean>

9
Creating a basic Controller Deloitte Training 2016

 Process
 Create the Controller class
 Implement the Controller interface

 Or extend one of the pre-built Controller implementations

 Create a setter to inject the service object


 Implement the handleRequest() method

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

 Extensive support for many different view technologies


 JSP, JSTL, Velocity, FreeMarker, JasperReports, PDF, Excel
 Views are represented using logical view names which are
returned by the Controller
 Can return an actual View class from the Controller if needed

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

• 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>

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

• Mapping request (URLs) to Controller


• Controlled by implementations of the
• HandlerMapping interface
• Useful out-of-the-box implementations
• BeanNameUrlHandlerMapping
• • Uses the Controller bean name as the URL
• mapping
• SimpleUrlHandlerMapping
• • Define a set of URL pattern to bean mappings
• Most out of the box implementations
• support Ant-style path matching

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

• Test with mock request, response and


• service
• Glass-box testing
• Ensure that the service is invoked as
• desired
• Fits well with a TDD approach
• Test a variety of interactions
• Controller with the request and response
• Controller with the service

28
Unit Testing a Controller Deloitte Training 2016

• private 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);
• }

29
contd.. Deloitte Training 2016

• 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);
• }

30
Integration Testing Deloitte Training 2016

• public 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());
• }
• }

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">&nbsp;</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

• 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!!

40
Creating a Validator Deloitte Training 2016

• 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");
• }
• }

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

 You have learned how to:


 Implement a basic Controller
 Creating a simple View
 To Configure a Spring MVC application and URL mappings
 Map views
 Grouping request handling logic with MultiActionController
 Handling form posts
 Adding validation
 Using data binding
 Adding error reporting
 Configuring form and success views

43

You might also like