Spring Web Views


Published on

Spring MVC View

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Spring Web Views

  1. 1. Rendering Views using Spring MVC
  2. 2. View Resolver A view resolver uses the logical view name in theModelAndView object returned from a controllerto look up a View bean to render results to the user. A view resolver is any bean that implementsorg.springframework.web.servlet.ViewResolver. Spring comes with several implementations ofViewResolver.
  3. 3. View Resolver
  4. 4. Spring MVC’s view resolversView resolver How it worksInternalResourceViewResolver Resolves logical view names into View objectsthat are rendered using template file resources(such as JSPs and Velocity templates)BeanNameViewResolver Looks up implementations of the View interfaceas beans in the Spring context, assuming thatthe bean name is the logical view nameResourceBundleViewResolver Uses a resource bundle (e.g., a properties file)that maps logical view names toimplementations of the View interfaceXmlViewResolver Resolves View beans from an XML file that isdefined separately from the application contextdefinition files
  5. 5. Template Views <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html> <head><title>Rantz For Vehicle</title></head> <body> <h2>Rantz for: ${vehicle.state} ${vehicle.plateNumber}</h2> <ul> <c:forEach items="${rants}" var="rant"> <li><c:out value="${rant.vehicle.state}"/>/ <c:out value="${rant.vehicle.plateNumber}"/> -- <c:out value="${rant.rantText}"/></li> </c:forEach> </ul> </body> </html>
  6. 6. InternalResourceViewResolver InternalResourceViewResolver resolves a logical view nameinto a View object that delegates rendering responsibility toa template located in the web application’s context. It takes the logical view name returned in a ModelAndViewobject and surrounding it with a prefix and a suffix to arriveat the path of a template within the web application. <bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
  7. 7. InternalResourceViewResolver When InternalResourceViewResolver resolves a view, ittakes the logical view name, prefixes it with /WEB-INF/jsp/, and suffixes it with .jsp to arrive at the path of theJSP that renders the output. The resolver then hands that path over to a View objectthat dispatches the request to the JSP. By default the View object is an InternalResourceView,which simply dispatches the request to the JSP to performthe actual rendering.x
  8. 8. JSTL View InternalResourceView can be replaced with JstlView by settingInternalResourceViewResolver’s viewClass property as follows: JstlView dispatches the request to a JSP similar toInternalResourceView. <bean id="viewResolver" class= "org.springframework.web.servlet.view. ➥ InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
  9. 9. BeanNameViewResolver It is a view resolver that matches logical view names upwith names of beans in the application context. When a controller returns a ModelAndView with alogical view name, BeanNameViewResolver will lookfor a bean named same as logical view name. <bean id="viewResolver"class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  10. 10. View Beans in separate XML file XmlFileViewResolver works much likeBeanNameViewResolver, but instead of looking for Viewbeans in the main application context, it consults aseparate XML file. <bean id="viewResolver"class="org.springframework.web.servlet.view.XmlFileViewResolver"> <property name="location"> <value>/WEB-INF/roadrantz-views.xml</value> </property> </bean> By default, XmlFileViewResolver looks for View definitionsin /WEB-INF/views.xml, but location property canoverride the default location.
  11. 11. Resource bundles ResourceBundleViewResolver is another way of resolving Views byname. ResourceBundleViewResolver manages view definitions in a propertiesfile instead of XML. <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views" /> </bean> The basename property tells the ResourceBundleViewResolver how toconstruct the names of the properties files that contain View definitions. The View definitions are listed in views.properties as follows: rantsRss.class=com.roadrantz.mvc.RantRssView The first part is the logical name of the View as returned inModelAndView. The second part, class, indicates setting of the class name of the Viewimplementation that should render the output for the rantsRss view. It gives advantage of internationalization as it could return a differentView implementation for the same logical view name, based on theuser’s Locale
  12. 12. Choosing a view resolver When the application isn’t internationalized,InternalResourceViewResolver is preferred as it is simple andtersely defined. When the views are rendered using a custom Viewimplementation (e.g., RSS, PDF, Excel, images, etc.), thenBeanNameViewResolver and XmlFileViewResolver is preferredover ResourceBundleViewResolver because they allow to defineView beans in a Spring context configuration XML file. BeanNameViewResolver is preferred over XmlFileViewResolverwhen there are only a handful of View beans to be configured inDispatcherServlet without increasing the size of its context file. XmlFileViewResolver is used to separate the View beandefinitions into a separate file.
  13. 13. Multiple View Resolvers Multiple view resolvers can be declared by simply declaring all the view resolverbeans in the context configuration file. <bean id="viewResolver" class="org.springframework.web.servlet.view. ➥ InternalResourceViewResolver"> <property name="prefix"><value>/WEB-INF/jsp/</value></property> <property name="suffix"><value>.jsp</value></property> </bean> <bean id="beanNameViewResolver" class= ➥ "org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order"><value>1</value></property> </bean> <bean id="xmlFileViewResolver" class= ➥ "org.springframework.web.servlet.view.XmlFileViewResolver"> <property name="location"> <value>/WEB-INF/views.xml</value> </property> <property name="order"><value>2</value></property> </bean>
  14. 14. Multiple View Resolvers When more than one view resolver resolves to thesame logical view name, an order property is set oneach of the view resolvers. The order property helps Spring to determine whichresolver has priority over the others when a logicalview name is ambiguous among more than oneresolver. The exception to this rule isInternalResourceViewResolver, which is always the lastview resolver in the chain.
  15. 15. JSP templates: Binding form data <form method="POST" action="addRant.htm"> <b>State: </b><input type="text“name="rant.vehicle.state"/><br/> <b>Plate #: </b> <input type="text" name="rant.vehicle.plateNumber"/><br/> <textarea name="rant.rantText" rows="5“ cols="50"></textarea> <input type="submit"/> </form> The names of the form fields are used to tell Spring whichproperties of the command object (rant) to populate withthe form data when the form is submitted.
  16. 16. JSP templates: Binding form data The form-binding JSP tags enables to redisplay the entered data in the fieldsafter an error. The following JSP directive is added for the tag: <%@ taglib prefix="form“ uri="http://www.spring.org/tags/form"%> The path attribute defines the command property for <form:input> and<form:textarea>. The <form:form> tag sets the command context for the form tags containedwithin it through the value of the commandName attribute. <form:form method="POST" action="addRant.htm"commandName="rant"> <b>State: </b><form:input path="vehicle.state" /><br/> <b>Plate #: </b><form:input path="vehicle.plateNumber" /> <br/> <form:textarea path="rantText" rows="5" cols="50" /> <input type="submit"/> </form:form> Binding-Form tags not only enables the command to be populated with thefield values, but if the form must be redisplayed after an error, the fields will beautomatically populated with the data that caused the error
  17. 17. Rendering externalized messages The <spring:message> renders a message from anexternal message properties file to the output view. Using <spring:message> an externalized message canbe referenced in the JSP page and have the actualmessage rendered when the view is rendered.
  18. 18. Rendering externalized messages The <spring:message> tag is used by importing the spring tag library asfollows: <%@taglib prefix="spring“uri="http://www.springframework.org/tags"%> <spring:message code="field.state" /> ResourceBundleMessageSource resolves the message codes to actualvalues of <spring:message>. <bean id="messageSource“class="org.springframework.context.support. ➥ ResourceBundleMessageSource"> <property name="basename" value="messages" /> </bean> The bean named messageSource is used by Spring to look for a messagesource. The location of the message properties file is in the classpath with thefile name determined by the basename property with “.properties” asfile extension.
  19. 19. Rendering externalized messages Sample messages.properties: field.state=State: field.plateNumber=Plate #: field.rantText=Rant text: title.addRant=Add a rant If the user has their locale and language settings set forSpanish, the message properties will be resolved frommessages_es.properties instead of the defaultmessages.properties file.
  20. 20. Displaying errors Spring uses Validator interface or Commons Validatorfor validation. A failed validation results in a message code beingplaced in the Errors object while the actual errormessage resides in an external properties file. The <form:errors> tag renders externalized errormessages based on error codes in the Errors object. The <form:errors> tag looks for any error messagecodes associated with the field (which is specified withthe path attribute) and then tries to resolve thosemessages from an external properties file.
  21. 21. Displaying errors <form:form method="POST" action="addRant.htm“ commandName="rant"> <b><spring:message code="field.state" /></b> <form:input path="vehicle.state" /> <form:errors path="vehicle.state" cssClass="error"/><br/> <input type="submit"/> </form:form> The error messages is configured in its own properties file as follows: <bean id="messageSource" class="org.springframework.context.support. ➥ ResourceBundleMessageSource"> <property name="basenames"> <list> <value>messages</value> <value>errors</value> </list> </property> </bean> The following excerpt from /WEB-INF/classes/errors.properties: required.state=State is required. invalid.plateNumber={0} is an invalid license plate number.
  22. 22. Jakarta Tiles: Laying out pages <%@ taglib prefix="tiles" uri="http://jakarta.apache.org/struts/tags-tiles" %> <html> <head> <title> <tiles:getAsString name="title"/> </title> </head> <body> <table width="100%" border="0"> <tr> <td><tiles:insert name="header"/></td> </tr> <tr> <td valign="top" align="left"> <tiles:insert name="content"/></td> </tr> <tr> <td> <tiles:insert name="footer"/> </td> </tr> </table> </body> </html>
  23. 23. Tiles: Laying out pages The Tiles <tiles:insert> JSP tag to include content into the template. The details of where the included content originates are specified in the Tiles definitionxml file. The Template and Homepage is defined as follows: <tiles-definitions> <definition name="template" page="/WEB-INF/jsp/rantzTemplate.jsp"> <put name="title" value="RoadRantz"/> <put name="header" value="/WEB-INF/jsp/header.jsp"/> <put name="content“ value="/WEB-INF/jsp/defaultContentPage.jsp"/> <put name="footer" value="/WEB-INF/jsp/footer.jsp"/> </definition> ……………………………….................................................................................. <definition name="home" extends="template"> <put name="title" value="Welcome to RoadRantz" /> <put name="content" value="/WEB-INF/jsp/home.jsp"/> </definition> </tiles-definitions>
  24. 24. Tiles: Laying out pages Extending template ensures that the homepage willinherit all of its component definitions. The title and the content is overridden to have aunique title and unique content for each page. The Tiles can be integrated into Spring MVC byfollowing steps: ■ Configuring a TilesConfigurer to load the Tilesdefinition file. ■ Declaring a Spring MVC view resolver to resolvelogical view names to Tiles definitions.
  25. 25. Configuring Tiles Spring comes with TilesConfigurer bean that loads Tiles configurationfiles and makes them available for rendering Tiles views. To load the Tiles configuration into Spring, a TilesConfigurer instanceis declared as follows: <bean id="tilesConfigurer" class="org.springframework. ➥ web.servlet.view.tiles.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/roadrantz-tiles.xml</value> </list> </property> </bean> The definitions property is given a list of Tiles definition files to load.
  26. 26. Resolving Tiles views A view resolver is configured to direct the user to a pagedefined by Tiles, completing the Tiles integration intoSpring MVC. InternalResourceViewResolver is configured to resolve theviews as definitions in a Tiles definition file, thus settingviewClass property to use a TilesJstlView. <bean id="viewResolver“class="org.springframework.web.servlet.view. ➥ InternalResourceViewResolver"> <property name="viewClass“ value="org.springframework.web.servlet.view.tiles. ➥ TilesJstlView"/> </bean>
  27. 27. Resolving Tiles views There are two types of view classes in Tiles: TilesView andTilesJstlView. TilesJstlView places the localization information into therequest for JSTL pages, supporting internationalization. When the InternalResourceViewResolver is configuredwith TilesJstlView (or TilesView), it resolve views bylooking in the Tiles definition file(s). If a <definition> in the Tiles definition file has a samename that matches the logical view name, it is used torender the page to the user. HomeController returns the following ModelAndView: return new ModelAndView("home", "rantz", recentRants); Hence, TilesView looks for the view definition “home” inthe Tiles configuration matching the logical name “home”.
  28. 28. Creating Tile Controllers To display common values on all the view pages, all theapplication controller classes need to add the requestvariable in the modelMap as follows: modelMap.add("rantsToday",rantService.getRantsForDay(new Date()).size(); In Tiles, each component on a page can have its owncontroller. Tiles controllers unlike Spring MVC controller, areassociated with Tiles components so that eachcomponent can perform functionality specific to thatcomponent.
  29. 29. Creating Tile Controllers public class HeaderTileController extends ComponentControllerSupport { public HeaderTileController() {} protected void doPerform(ComponentContext componentContext, HttpServletRequest request, HttpServletResponse response) throws Exception { RantService rantService = getRantService(); int rantsToday = rantService.getRantsForDay(new Date()).size(); componentContext.putAttribute("rantsToday", rantsToday); } private RantService getRantService() { return (RantService) getApplicationContext().getBean( "rantService"); } } ComponentControllerSupport is a Spring-specific extension of Tiles’s ControllerSupportclass which makes the Spring application context available via getApplicationContext()method. The component controller is associated with the view component as follows: <definition name=".header" page="/WEB-INF/jsp/header.jsp" controllerClass="com.roadrantz.tiles.HeaderTileController" />
  30. 30. Velocity: Defining Velocity view <html> <head><title>Rantz</title></head> <body> <h2>Rantz:</h2> <a href="addRant.htm">Add rant</a><br/> <ul> #foreach($rant in $rants) <li>${rant.vehicle.state}/ ${rant.vehicle.plateNumber} -- ${rant.rantText}</li> #end </ul> </body> </html> Velocity isn’t tag-based and uses Velocity Template Language (VTL)—forcontrol flow and other directives. In above home.vm, the #foreach directive is used to loop through a list ofrants, displaying rant details with each iteration.
  31. 31. Configuring Velocity engine The Velocity engine is configured by VelocityConfigurer bean in the Spring asfollows: <bean id="velocityConfigurer" class= ➥ "org.springframework.web.servlet.view.velocity. ➥ VelocityConfigurer"> <property name="resourceLoaderPath" value="WEB-INF/velocity/" /> <property name="velocityProperties"> <props> <prop key="directive.foreach.counter.name">loopCounter</prop> <prop key="directive.foreach.counter.initial.value">0</prop> </props> </property> </bean> The resourceLoaderPath property enables Velocity to find its templates. The behavior of Velocity is mostly configured using a velocity.properties file. The VelocityConfigurer, can also set those configuration details by setting thevelocity-Properties property as above.
  32. 32. Resolving Velocity views Velocity template is configured by VelocityViewResolver(similar to InternalResourceViewResolver in JSP) asfollows; <bean id="viewResolver" class="org.springframework.web.servlet.view. ➥ velocity.VelocityViewResolver"> <property name="suffix" value=".vm" /> </bean> When the ModelAndView object returns view’s logicalname as home, home is suffixed with .vm to create thetemplate name “home.vm”, which is later fetched byVelocityViewResolver from the WEB-INF/velocity/ path.
  33. 33. Velocity:Formatting dates/numbers Velocity has tools for date and number formatting which are enabled using theVelocityViewResolver attributes, dateToolAttribute andnumberToolAttribute properties: <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="suffix" value=".vm" /> <property name="dateToolAttribute"> <value>dateTool</value> </property> <property name="numberToolAttribute"> <value>numberTool</value> </property> </bean> The Date is format as follows: $dateTool.format("FULL", rant.postedDate) The first parameter is the pattern string similar to Java SimpleDateFormat withpossible values FULL, LONG, MEDIUM, SHORT, or DEFAULT.
  34. 34. Request & Session attributes Velocity template accesses the data passed through the model Map in theModelAndView object. VelocityViewResolver enables to copy the request/session attributes into themodel using the exposeRequestAttributes and exposeSessionAttributesproperties as follows: <bean id="viewResolver" class="org.springframework. ➥ web.servlet.view.velocity.VelocityViewResolver"> … <property name="exposeRequestAttributes"> <value>true</value> </property> <property name="exposeSessionAttributes"> <value>true</value> </property> </bean> The default values for both the properties is false. Setting the property values to true enabling both the request and sessionattributes to be copied into the model and visible in the Velocity template.
  35. 35. Velocity: Binding form fields Spring provides a set of Velocity macros which provideequivalent functionality of binding form fields toproperties and displaying error messages to Spring’s JSP taglibraries. The form-binding macros render HTML form elementswhose values are bound to a property of a command object. The first parameter specifies the specific property to whichthe macros are bound. Most of the macros also have a parameter to specifyadditional attributes to be placed on the rendered HTMLelements. The Spring macros need to be enabled before use, bysetting the exposeSpringMacroHelpers property ofVelocityViewResolver to true.
  36. 36. Spring Velocity MacrosMacro Purpose#springFormCheckboxes Renders a set of check boxes#springFormHiddenInput Renders a hidden field bound to command object#springFormInput Renders a text field bound to a command object#springFormMultiSelect Renders a selection list allowing multiple selection.#springFormPasswordInput Renders a password field.#springFormRadioButtons Renders a set of radio buttons#springFormSingleSelect Renders a selection list, allowing single selection.#springFormTextarea Renders a text area bound to a command object#springMessage Renders a message externalized in a resourcebundle.#springMessageText Renders a message externalized in a resourcebundle, with a default value if message not found#springShowErrors Renders validation errors.#springUrl Renders an absolute URL given a relative URL.
  37. 37. FreeMarker: Constructing View <html> <head><title>Rantz</title></head> <body> <h2>Rantz:</h2> <a href="addRant.htm">Add rant</a><br/> <ul> <#list rants as rant> <li>${rant.vehicle.state}/ ${rant.vehicle.plateNumber} -- ${rant.rantText}</li> </#list> </ul> </body> </html> Similar to Velocity, Freemarker uses the ${} notation as an expression languageto display attribute values.
  38. 38. FreeMarker: Configuring engine FreeMarkerConfigurer is declared in the context configuration file asfollows: <bean id="freemarkerConfig“ class="org.springframework.web.servlet.view. ➥ freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="WEB-INF/freemarker/" /> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">3600</prop> </props> </property> </bean> The templateLoaderPath property tells FreeMarker where to find thetemplates. Additional FreeMarker settings can be configured by setting them asproperties through the freemarkerSettings property The template_update_delay property is used to set the delay time for thetemplate to check for updates inorder to reload and reparse the templates.
  39. 39. FreeMarker: Resolving views The view resolver for FreeMarker is declared as follows: <bean id="viewResolver" class="org.springframework.web.servlet.view. ➥ freemarker.FreeMarkerViewResolver"> <property name="suffix" value=".ftl" /> </bean> Template resources are resolved by prefixing a view’slogical name with the value of the prefix property and aresuffixed with the value of the suffix property. Similar to VelocityViewResolver, only the suffix property isset, because the template path is already defined inFreeMarkerConfigurer’s templateLoaderPath property.
  40. 40. Freemarker: Request Attributes FreeMarkerViewResolver allows to expose request and session attributes asvariables in a FreeMarker template by setting either theexposeRequestAttributes or exposeSessionAttributes property (or both) totrue: <bean id="viewResolver“ class="org.springframework.web.servlet.view. ➥ freemarker.FreeMarkerViewResolver"> … <property name="exposeRequestAttributes"> <value>true</value> </property> <property name="exposeSessionAttributes"> <value>true</value> </property> </bean> This results both request and session attributes are copied into the template’sset of attributes and are available to display using FreeMarker’s expressionlanguage.
  41. 41. FreeMarker: Binding form fields Spring provides a set of FreeMarker macros mirroring thefunctionality of the Velocity macros. FreeMarker version uses <@spring.formInput> instead of#springFormInput and <@spring.formTextarea> instead of#springFormTextarea. FreeMarker macros must be imported unlike Velocity in whichthe macros were automatically available. The FreeMarker macros can be enabled to use by setting theexposeMacroHelpers property of FreeMarkerViewResolver totrue: <bean id="viewResolver" class="org.springframework.web.servlet.view. ➥ freemarker.FreeMarkerViewResolver"> <property name="suffix" value=".ftl" /> <property name="exposeSpringMacroHelpers" value="true" /> </bean>
  42. 42. Spring Freemarker MacrosMacro Purpose<@spring.formCheckboxes /> Renders a set of check boxes<@spring.formHiddenInput/> Renders a hidden field bound to command object<@spring.formInput /> Renders a text field bound to a command object<@spring.formMultiSelect /> Renders selection list allowing multiple selection.<@spring.formPasswordInput/> Renders a password field.<@spring.formRadioButtons /> Renders a set of radio buttons<@spring.formSingleSelect /> Renders a selection list, allowing single selection.<@spring.formTextarea /> Renders a text area bound to a command object<@spring.message /> Renders a message externalized in a resourcebundle.<@spring.messageText /> Renders a message externalized in a resourcebundle, with a default value if message not found<@spring.showErrors /> Renders validation errors.<@spring.url /> Renders an absolute URL given a relative URL.