+ All Categories
Home > Documents > Spring MVC Views

Spring MVC Views

Date post: 01-Jan-2016
Category:
Upload: teegan-chandler
View: 51 times
Download: 1 times
Share this document with a friend
Description:
Spring MVC Views. Rendering custom views with Spring MVC. Topics in this Session. Revisiting Views Rendering PDF Documents Rendering Excel Spreadsheets Generating Jasper Reports Ajax Integration Internationalization. Topics in this Session. Revisiting Views Rendering PDF Documents - PowerPoint PPT Presentation
46
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Views Rendering custom views with Spring MVC
Transcript
Page 1: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Spring MVC Views

Rendering custom views with Spring MVC

Page 2: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 3: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 4: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4

Revisiting Views

• A View is a simple strategy interface• Spring provides implementations for major

view technologies• You can write your own

– Easily unit tested using MockHttpServletRequest and MockHttpServletResponse

Page 5: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5

Revisiting ViewResolvers

• A ViewResolver is used by the DispatcherServlet to resolve logical view names to View implementations– InternalResourceViewResolver resolves view names to a

resource path (typically a JSP)– BeanNameViewResolver resolves view names to the

name of a Spring bean

Page 6: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6

View Integration

• Supported View Technologies– JSP / JSTL– Apache Velocity– Freemarker– Adobe PDF– Microsoft Excel– Jasper Reports– XML / XSLT

Page 7: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7

View Independence

• Views are completely orthogonal to the Controller– The keys within the Model form a contract

• The same Controller can be used to return different views of the same model– HTML view– PDF view– Excel view

Page 8: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 9: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9

Rendering PDF Documents

• The AbstractPdfView class integrates with iText for generating PDFs (see http://www.lowagie.com/iText)

• Provides a single abstract template method

public class RewardsListPdfView extends AbstractPdfView { public void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest request,

HttpServletResponse response) throws Exception {

List<Reward> rewards = (List<Reward>) model.get(“rewards”); for (Reward reward : rewards) { document.add(new Paragraph(“..”)); // … } }}

public class RewardsListPdfView extends AbstractPdfView { public void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest request,

HttpServletResponse response) throws Exception {

List<Reward> rewards = (List<Reward>) model.get(“rewards”); for (Reward reward : rewards) { document.add(new Paragraph(“..”)); // … } }}

Contract with the Controller

Page 10: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10

Configure the Existing Controller to use the PDF View

• No need to modify the RewardsController to support the new View– Assuming the view name is parameterizable

• Define one configuration of the Controller for each View

Page 11: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11

Update the Servlet Application Context

<bean id=“abstractRewardsListController” class=“rewardsadmin.RewardsListController” abstract=“true”> <constructor-arg ref=“rewardLookupService” /></bean>

<bean name=“/rewards/list.html” parent=“abstractRewardsListController”> <property name=“viewName” value=“list”/></bean>

<bean name=“/rewards/list.pdf” parent=“abstractRewardsListController”> <property name=“viewName” value=“listPdf”/></bean>

<bean id=“abstractRewardsListController” class=“rewardsadmin.RewardsListController” abstract=“true”> <constructor-arg ref=“rewardLookupService” /></bean>

<bean name=“/rewards/list.html” parent=“abstractRewardsListController”> <property name=“viewName” value=“list”/></bean>

<bean name=“/rewards/list.pdf” parent=“abstractRewardsListController”> <property name=“viewName” value=“listPdf”/></bean>

/WEB-INF/rewardsadmin-servlet-config.xml

Page 12: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12

Defining the PDF View

• RewardsListPdfView needs to be defined as a Spring bean

• The DispatcherServlet needs to be able to access the RewardsListPdfView bean– The existing InternalResourceViewResolver resolves to

JSPs

• Need to plug in an extra ViewResolver strategy to locate the PDF view– Scales to handle any custom view implementations

Page 13: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13

Defining the View and ViewResolver

<bean class=“org.springframework.web.servlet.view. InternalResourceViewResolver”> ….</bean>

<bean name=”listPdf” class=“rewardsadmin.RewardsListPdfView”/>

<bean class=“org.springframework.web.servlet.view. BeanNameViewResolver”> <property name=“order” value=“0”/></bean>

<bean class=“org.springframework.web.servlet.view. InternalResourceViewResolver”> ….</bean>

<bean name=”listPdf” class=“rewardsadmin.RewardsListPdfView”/>

<bean class=“org.springframework.web.servlet.view. BeanNameViewResolver”> <property name=“order” value=“0”/></bean>

The existing ViewResolver

The new View

The new ViewResolver

Page 14: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 15: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15

Rendering Excel Spreadsheets

• AbstractExcelView integrates with POI to generate Excel compatible Spreadsheets – (see http://jakarta.apache.org/poi/index.html)

public class RewardsListExcelView extends AbstractExcelView { public void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { List<Reward> rewards = (List<Reward>) model.get(“rewards”); HSSFSheet sheet = workbook.createSheet(“rewards”); for (int i = 0; i < rewards.size(); i++) {

setText(getCell(sheet, i, 0), “..”); … } }}

public class RewardsListExcelView extends AbstractExcelView { public void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { List<Reward> rewards = (List<Reward>) model.get(“rewards”); HSSFSheet sheet = workbook.createSheet(“rewards”); for (int i = 0; i < rewards.size(); i++) {

setText(getCell(sheet, i, 0), “..”); … } }}

Contract with the Controller

Page 16: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16

Register the Controller with the DispatcherServlet

<bean id=“abstractRewardsListController”> ….</bean>

<bean name=“/rewards/list.xls” parent=“abstractRewardsListController”> <property name=“viewName” value=“listExcel”/></bean>

<bean name=“/rewards/list.html” parent=“abstractRewardsListController”> <property name=“viewName” value=“list”/></bean>

<bean name=“/rewards/list.pdf” parent=“abstractRewardsListController”> <property name=“viewName” value=“listPdf”/></bean>

<bean id=“abstractRewardsListController”> ….</bean>

<bean name=“/rewards/list.xls” parent=“abstractRewardsListController”> <property name=“viewName” value=“listExcel”/></bean>

<bean name=“/rewards/list.html” parent=“abstractRewardsListController”> <property name=“viewName” value=“list”/></bean>

<bean name=“/rewards/list.pdf” parent=“abstractRewardsListController”> <property name=“viewName” value=“listPdf”/></bean>

Page 17: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17

Defining the Excel View

<bean name=“listExcel” class=“rewardsadmin.RewardsListExcelView”/>

<bean name=”listPdf” class=“rewardsadmin.RewardsListPdfView”/>

<bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>

…</bean>

<bean class=“org.springframework.web.servlet.view.BeanNameViewResolver”> <property name=“order” value=“0”/></bean>

<bean name=“listExcel” class=“rewardsadmin.RewardsListExcelView”/>

<bean name=”listPdf” class=“rewardsadmin.RewardsListPdfView”/>

<bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>

…</bean>

<bean class=“org.springframework.web.servlet.view.BeanNameViewResolver”> <property name=“order” value=“0”/></bean>

Resolves both ‘listPdf’ and ‘listExcel’

Page 18: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 19: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19

Overview of Jasper Reports

• Jasper Reports is a very sophisticated document generator– Capable of producing PDFs, Excel, HTML and CSV

• Report designs are expressed in a Jasper Reports XML format

Page 20: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20

Jasper Report Components (1)

• Reports– Templates for rendering information about a model

• Sub Reports– A report may contain one or more sub reports

• JRDataSource– Source of the model that is used to populate a report

Page 21: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21

Jasper Reports Components (2)

• JRExporter– Strategy class to render the report (HTML, PDF, etc.)

• .jrxml– The XML report design

• .jasper– The compiled XML report (generated by an Ant task

or dynamically compiled at runtime)

Page 22: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22

Jasper Report Views

• Spring provides a number of Jasper Report views for rendering specific formats– JasperReportsPdfView– JasperReportsCsvView– JasperReportsExcelView– JasperReportsHtmlView

• Alternatively ConfigurableJasperReportsView allows you to provide your own JRExporter

Page 23: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23

The Contract when Using Jasper Reports

• The Model provides the contract between the Controller and the View

• The View implementation should not leak into the Controller

• For Jasper Reports, this contract can be quite complex– Each report requires a JRDataSource– One for each sub report

Page 24: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24

Specifying the JRDataSource

• Spring will automatically convert a java.util.Collection into a JRDataSource– By default, it will use the first Collection in the Model

• Each sub report requires its own JRDataSource– The name of the JRDataSource is configured in the

master report.jrxml file– This name will be used as a key in the model to locate

either a JRDataSource or a Collection

Page 25: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25

Replacing the Pdf and Excel Views with Jasper Report Views

• The Report must be designed and stored in a .jrxml file– /WEB-INF/jasper/rewards/list.jrxml

• Replace the RewardsListPdfView definition with the JasperReportsPdfView definition

• Replace the RewardsListExcelView definition with the JasperReportsExcelView definition

Page 26: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26

Update the View Definitions

<bean id=“abstractJasperReportsListView” abstract=“true”> <property name=“url” value=“/WEB-INF/jasper/rewards/list.jrxml”/> <property name=“reportDataKey” value=“rewards”/></bean>

<bean name=“listPdf” parent=“abstractJasperReportsListView” class=“org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView”/>

<bean name=“listExcel” parent=“abstractJasperReportsListView” class=“org.springframework.web.servlet.view.jasperreports.JasperReportsExcelView”/>

<bean id=“abstractJasperReportsListView” abstract=“true”> <property name=“url” value=“/WEB-INF/jasper/rewards/list.jrxml”/> <property name=“reportDataKey” value=“rewards”/></bean>

<bean name=“listPdf” parent=“abstractJasperReportsListView” class=“org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView”/>

<bean name=“listExcel” parent=“abstractJasperReportsListView” class=“org.springframework.web.servlet.view.jasperreports.JasperReportsExcelView”/>

Contract with the Controller

Page 27: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 28: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28

Ajax Overview

• “Asynchronous JavaScript And Xml”• Allows asynchronous refreshing of individual

parts of a web page instead of the whole page– Greatly improves user experience– Reduces network traffic

Page 29: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29

Ajax Use Cases

• Typical use cases for Ajax include– Form validation (validating the field as you type)– Displaying potential results as you enter search criteria– Adding new entries without refreshing the page– The list is endless really; it is an enabling technology

Page 30: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30

Introduction to DWR

• Many different libraries and frameworks provide Ajax behavior

• Direct Web Remoting (DWR) integrates very well with Spring MVC– Very popular and well established framework

Page 31: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31

Exposing Server Side Components

• DWR exposes server side components for invocation via JavaScript

• DWR creates a JavaScript proxy which will perform a RPC to the server side component– DWR takes care of marshalling and sending your

POJOs across the wire

• Ajax is asynchronous, so when invoking a server side method, a call-back must be registered

Page 32: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32

Integrating DWR with Spring MVC

• DWR requires its own Controller which handles all DWR requests– Executes the RPC calls– Dynamically creates a JavaScript file for each exposed

service

• Each service should be exported by DWR

Page 33: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33

Configuring DWR on the Server

<beans xmlns=“http://www.springframework.org/schema/beans” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:dwr=“http://www.directwebremoting.org/schema/spring” xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-2.0.xsd” >

<dwr:controller id=“dwrController”/>

<bean id=“echoService” class=“example.EchoService”> <dwr:remote javascript=“EchoService”/> <property … /> </bean>

</beans>

<beans xmlns=“http://www.springframework.org/schema/beans” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:dwr=“http://www.directwebremoting.org/schema/spring” xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-2.0.xsd” >

<dwr:controller id=“dwrController”/>

<bean id=“echoService” class=“example.EchoService”> <dwr:remote javascript=“EchoService”/> <property … /> </bean>

</beans>

Defaults to “/dwr”

Name of the JavaScript file

Page 34: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34

Configuring DWR on the Client

• DWR provides an engine.js JavaScript file which provides the DWR infrastructure

• DWR also generates one JavaScript file for each exported server side component

<script type=“test/javascript” src=“/dwr/engine.js”></script>

<script type=“test/javascript” src=“/dwr/interface/EchoService.js”></script>

<script type=“test/javascript” src=“/dwr/engine.js”></script>

<script type=“test/javascript” src=“/dwr/interface/EchoService.js”></script>

The DWR engine

Remote Service

Page 35: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35

Using DWR on the Client

<html><head>function callServer(message) { EchoService.echo(message, echoBack);}

function echoBack(message) { document.getElementById(‘response’).value=‘Server said [’ + message + ‘]’;}</head>

<body> <input type=“text” name=“prompt” onchange=“callServer(this.value)”/> <input type=“text” id=“response”/></body></html>

<html><head>function callServer(message) { EchoService.echo(message, echoBack);}

function echoBack(message) { document.getElementById(‘response’).value=‘Server said [’ + message + ‘]’;}</head>

<body> <input type=“text” name=“prompt” onchange=“callServer(this.value)”/> <input type=“text” id=“response”/></body></html>

The remote invocation

Handling the responseThe Server Component API

Page 36: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36

Walkthough of DWR

function callServer(message) { EchoService.echo(…);}

Spring ApplicationSpring Application

function echoBack(result) { document.getElement….}

Spring ApplicationSpring Application

Time

Page 37: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37

Topics in this Session

• Revisiting Views• Rendering PDF Documents• Rendering Excel Spreadsheets• Generating Jasper Reports• Ajax Integration• Internationalization

Page 38: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38

Internationalization Overview

• The Internet is a worldwide entity, and web applications should take that into consideration– Views should be rendered in the native language of

the visitor

• The JDK supports internationalization through the use of MessageBundles and Locales– The Locale represents the user’s Country and

Language

Page 39: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39

Introduction to Resource Bundles

• ResourceBundles externalize all language sensitive strings– Labels– Messages– Validation messages

• Each Locale has its own ResourceBundle using a well defined naming convention– labels_en_GB.properties– labels_en_US.properties– etc.

Page 40: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40

How does Spring Support This?

• Spring provides a MessageSource Strategy interface to support message resolution

• There are two implementations, both support Java Resource Bundles (property files)– ResourceBundleMessageSource– ReloadableResourceBundleMessageSource

Page 41: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41

Defining a MessageSource

<beans> <bean class=“org.sfw.ResourceBundleMessageSource”> <property name=“basenames”> <list> <value>exceptions</value> <value>labels</value> </list> </property> </bean></beans>

<beans> <bean class=“org.sfw.ResourceBundleMessageSource”> <property name=“basenames”> <list> <value>exceptions</value> <value>labels</value> </list> </property> </bean></beans>

Loads the resource bundles exceptions_XX_YY.properties and labels_XX_YY.properties from the classpath

Page 42: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42

Resolving Validation Error Keys

• When specifying validation errors, an error-key is specified (e.g. “error.age.too_young”)

• The error-key is the key in the resource bundle• Spring will automatically resolve this with the

registered resource bundles based on the current user’s Locale– exceptions_en_GB.properties– exceptions_en_US.properties– etc.

Page 43: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 43

Retrieving Locale Specific Labels

• You can also arbitrarily query the resource bundle– messageSource.getMessage(key, args, locale);– <spring:message key=“employee.age.label”/>

• The current Locale is determined by the defined LocaleResolver, and the appropriate resource bundle will be chosen– labels_en_GB.properties– labels_en_US.properties

Page 44: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 44

Determining the Locale

• The mechanism of determining the current Locale is provided by a LocaleResolver

public interface LocaleResolver {

Locale getLocale(HttpServletRequest request);

void setLocale(HttpServletRequest request, HttpServletReponse response, Locale locale);

}

public interface LocaleResolver {

Locale getLocale(HttpServletRequest request);

void setLocale(HttpServletRequest request, HttpServletReponse response, Locale locale);

}

Page 45: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 45

Defining a LocaleResolver

• Spring MVC provides a number of LocaleResolvers– AcceptHeaderLocaleResolver (default)– CookieLocaleResolver– SessionLocaleResolver– Write your own

• Simply define it as a bean in the Servlet’s ApplicationContext

<beans> <bean class=“org.sfw.CookieLocaleResolver”/></beans>

<beans> <bean class=“org.sfw.CookieLocaleResolver”/></beans>

Page 46: Spring MVC Views

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 46

Summary

• Spring integrates with a wide range of best of breed view technologies

• Spring’s strict implementation of MVC enables multiple renditions of the same Model without impacting the Controller

• Ajax is a very powerful technology which is changing the way developers and users think about web applications– DWR and Spring enable developers to build richer,

more interactive web applications


Recommended