0% acharam este documento útil (0 voto)
23 visualizações58 páginas

1 Spring MVC

Enviado por

dhanunjay.eng
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
23 visualizações58 páginas

1 Spring MVC

Enviado por

dhanunjay.eng
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 58

Modulo II

Spring-MVC

Prof. Ismael H F Santos

April 05 Prof. Ismael H. F. Santos - [email protected] 1

Bibliografia
„ Spring in Action
„Craig Walls and Ryan Breidenbach
„ Professional Java Development with Spring
„Rod Johnson, Juergen Hoeller and Team

April 05 Prof. Ismael H. F. Santos - [email protected] 2

1
Ementa
„ Spring in the Web Tier
„ Spring in the Middle Tier
„ Spring-MVC

April 05 Prof. Ismael H. F. Santos - [email protected] 3

WebApp
Histórico
Programação
Web

April 05 Prof. Ismael H. F. Santos - [email protected] 4

2
Histórico Programação Web

April 05 Prof. Ismael H. F. Santos - [email protected] 5

Histórico Programação Web

April 05 Prof. Ismael H. F. Santos - [email protected] 6

3
Container Web – Java
„ Container = gerenciador de objetos com ciclo de vida
específico;
„ Tem parte das funcionalidades de um Servidor de
Aplicações J2EE;
„ Ex.: Tomcat, Jetty, Resin, WebLogic, Oracle AS,
WebSphere, JBoss, etc.
„ JSR 53 = Servlet 2.3 e JSP 1.2;
„ JSR 152 = JSP 2.0;
„ JSR 154 = Servlet 2.4;
„ JSR 245 = JSP 2.1;
„ JSR 315 = Servlet 3.0;
„ Os containers implementam as especificações.

April 05 Prof. Ismael H. F. Santos - [email protected] 7

Servlet Container

April 05 Prof. Ismael H. F. Santos - [email protected] 8

4
Java Server Pages

April 05 Prof. Ismael H. F. Santos - [email protected] 9

Servlet Controller

April 05 Prof. Ismael H. F. Santos - [email protected] 10

5
“Separation of concerns”
„ Páginas Web (JSP, HTML, etc.) cuidam da parte visual;

„ Servlet central faz o controle mediante configuração;

„ Ações manipulam classes de lógica de negócio


(modelo).

April 05 Prof. Ismael H. F. Santos - [email protected] 11

Model-View-Controller (MVC)
Design Pattern
„ MVC
„ Clearly separates business, navigation
and presentation logic. It´s a proven Controller
mechanism for building a thin, clean
web-tier
„ Model
„ The domain-specific representation of
the information on which the View Model
application operates.
„ View
„ Renders the model into a form suitable
for interaction, typically a user interface Note: the solid lines
indicate a direct
element. association, and the
„ Controller dashed line indicate an
indirect association
„ Processes and responds to events,
http://en.wikipedia.org/wiki/Model-view-controller
typically user actions, and may invoke
changes on the model.
April 05 Prof. Ismael H. F. Santos - [email protected] 12

6
Model-View-Controller (MVC)
Design Pattern
„ O que é o MVC
„ padrão projeto para o desenvolvimento de aplicações,
„ A implementação de aplicações usando este padrão são feitas
com recurso a frameworks, apesar de não ser obrigatória a
utilização de uma para seguir o padrão.
„ Objetivo do MVC
„ Isolar mudanças na GUI, evitando que estas mudanças
acarretem em mudanças na Camada de Negicos da Aplcação
(Application’s Domain Logic)
„ Vantagens
„ Facilita a manutenção
„ Changes to business logic are less likely to break the presentation
logic & vice-versa
„ Facilita o desenvolvimento por times multi-disciplinares:
„ desenvolvedores – creating robust business code
„ designers – building usable and engaging UIs
April 05 Prof. Ismael H. F. Santos - [email protected] 13

Model-View-Controller (MVC)
Design Pattern
„ Camadas e respectivas funções
„ Model:
„Define as regras de acesso e manipulação dos dados
„Armazenados em bases de dados ou ficheiros, mas nada
indica que sirva só para alojamento persistente dos dados.
„ Pode ser usado para dados em memória volátil, p.e.:
memória RAM, apesar não se verificar tal utilização com
muita frequência. Todas as regras relacionadas com
tratamento, obtenção e validação dos dados devem ser
implementados nesta camada.
„ View:
„ Responsável por gerar a forma como a resposta será
apresentada, página web, formulário, relatório, etc...
„ Controller:
„ Responsável por responder aos pedidos por parte do
utilizador. Sempre que um utilizador faz um pedido ao
servidor esta camada é a primeira a ser executada.
April 05 Prof. Ismael H. F. Santos - [email protected] 14

7
Front Controller (Servlet Controller)
„ Dispatcher Servlet - “Front Controller” implementation
„ A single Front Controller servlet that dispatches requests to
individual Controllers
„ Request routing is completely controlled by the Front Controller

„ A lógica do MVC é altamente generalizável;

„ Podemos listar mais de 50 frameworks diferentes:


Cocoon, Action Framework, Maverick, MyFaces, ….,
SpringMVC, Struts, Tapestry, WebWork, PHP, RubyOn
Raetc

April 05 Prof. Ismael H. F. Santos - [email protected] 15

Especificações do J2EE - Arquiteturas


de aplicação Web
„ Model 1
„ Recomendado para
projetos pequenos.
„ E/S: Java Server Pages
„ Lógica de negócio: Java
Beans e EJBs

„ Model 2
„ Recomendada para
projetos médios e
grandes.
„ Variação do padrão MVC
„ Controller: Servlets
„ Model: JavaBeans e EJBs
„ View: Java Server Pages

April 05 Prof. Ismael H. F. Santos - [email protected] 16

8
Futuro: WebBeans – JBoss Seam
„ JSR 299 – Web Beans;
„ Unificação dos modelos EJB 3 e JSF 2;
„ EJB 3 traz idéias bem-sucedidas: ORM, DI, etc., porém a
integração com JSF ainda é trabalhosa e tediosa.
„ Web Beans unifica os modelos de componentes; JBoss
Seam. O criador do Seam é Spec Lead do Web Beans.
„ Integração JSF – EJB3 (modelo de componentes unificado);
„ AJAX e jBPM integrados;
„ Gerenciamento de estado declarativo;
„ Bijection, Conversation e Workspaces;
„ Utilização de POJOs com anotações;
„ Testabilidade;
„ I18n, autenticação, depuração, URLs RESTful,
„ seam-gen, eventos, interceptadores, etc.
April 05 Prof. Ismael H. F. Santos - [email protected] 17

WebApp
Spring
WebTier

April 05 Prof. Ismael H. F. Santos - [email protected] 18

9
Spring MVC
„ Construído sobre o núcleo do Spring.
„ Acomoda várias tecnologias de view:
„ JSP, Velocity, Tiles, iText, POI etc. JSP, Velocity, Tiles,
iText, POI etc.
„ Pode ser combinado a outras web tiers:
„ Struts, WebWork, Tapestry etc. Struts, WebWork,
Tapestry etc.
„ Configurável via strategy interfaces.

April 05 Prof. Ismael H. F. Santos - [email protected] 19

Proposed Web App Layering

April 05 Prof. Ismael H. F. Santos - [email protected] 20

10
Alguns Frameworks MVC
„ Struts (Apache)
„ Frameworks e toolkits para aplicações web.
„ Voltado para o desenvolvimento de Model+Controller.
„ Público-alvo: desenvolvedores - http://struts.apache.org/
„ Velocity (Apache)
„ Template engine para referenciar objetos Java.
„ Voltado para o desenvolvimento da View.
„ Público-alvo: web designers
„ http://jakarta.apache.org/velocity/
„ Java Server Faces (Sun)
„ Tecnologia para construção de UIs web para aplicações Java.
„ Voltado para o desenvolvimento da View.
„ Público-alvo: desenvolvedores
„ http://java.sun.com/javaee/javaserverfaces/

April 05 Prof. Ismael H. F. Santos - [email protected] 21

Where Spring Framework Fits Into a


JEE Architecture
Optional
Hibernate, JPA
integration

April 05 Prof. Ismael H. F. Santos - [email protected] 22

11
Web App – Scenario 1

April 05 Prof. Ismael H. F. Santos - [email protected] 23

Web App – Scenario 2

April 05 Prof. Ismael H. F. Santos - [email protected] 24

12
Web App – Scenario 3

April 05 Prof. Ismael H. F. Santos - [email protected] 25

Web App – Scenario 4

April 05 Prof. Ismael H. F. Santos - [email protected] 26

13
Spring on the Web Tier – Spring MVC
„ Spring integrates nicely with Struts, WebWork, JSF,
Tapestry, Velocity and other web frameworks
„ Spring MVC, Spring’s own web framework. The Spring
MVC Framework offers a simple interface based
infrastructure for handing web MVC architectures
„ Spring MVC components are treated as first-class Spring
beans
„ Other Spring beans can easily be injected into Spring MVC
components
„ Spring MVC components are easy to test

April 05 Prof. Ismael H. F. Santos - [email protected] 27

Spring MVC – Key Interfaces


„ Controller
(org.springframework.web.servlet.mvc.Controller)
„ User created component for handling requests
„ Encapsulates navigation logic
„ Delegates to the service objects for business logic
„ Must implement ModelAndView handleRequest(request,
response)

„ This is the base controller interface, comparable to the notion of


a Struts Action.

April 05 Prof. Ismael H. F. Santos - [email protected] 28

14
Spring MVC – Key Interfaces
„ View (org.springframework.web.servlet.mvc.View)
„ Responsible for rendering output
„ Must implement void render(model, request, response)
„ This is the MVC view for a web interaction. Implementations are
responsible for rendering content, and exposing the model.

„ Model
„ To complete the MVC trio, note that the model is typically handled
as a java.util.Map which is returned with the view
„ the values of the model are available, for example in a JSP, using a
<jsp:useBean/> where the id corresponds to the key value in
the Map

April 05 Prof. Ismael H. F. Santos - [email protected] 29

Spring MVC – Key Interfaces


„ ModelAndView
„ Created by the Controller
„ Stores the Model data
„ Associates a View to the request
„ 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

April 05 Prof. Ismael H. F. Santos - [email protected] 30

15
MVC and Dependency Injection
„ 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>

April 05 Prof. Ismael H. F. Santos - [email protected] 31

Spring on the Web Tier: Integration


with Other Frameworks
„ Spring integrates nicely with other web frameworks with
two methodologies:
„ Look up Spring beans within Controllers/Actions via the
convenience static method:
„ WebApplicationContextUtils.

getWebApplicationContext(servletContext).getBean(“beanName”)

„ Configure the Controllers/Actions for the web framework in a


Spring BeanFactory and then use Spring provided proxies in the
actual web framework configuration
„ When available, this methodology is preferred
„ This approach lets you design your Controllers/Actions with
dependency injection and makes your Controller/Actions more
testable
April 05 Prof. Ismael H. F. Santos - [email protected] 32

16
WebApp
SpringMVC
application

April 05 Prof. Ismael H. F. Santos - [email protected] 33

Aplicação Básica
„ Web.xml Entry
„ Standard J2EE web container servlet definition
„ Establishes which and where listeners act on
requests

„ Bean Definitions
„ ${servlet-name}-servlet.xml
„ Beans unique to the the web context [created for
the configured Servlet dispatcher]
„ ApplicationContext.xml
„ Beans common to all contexts

April 05 Prof. Ismael H. F. Santos - [email protected] 34

17
Aplicação Básica - Web.xml
„ ${webapp}\WEB-INF\web.xml
Standard Servlet
web.xml:
<web-app>

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name> springmvc</servlet-name>
<url-pattern>/hello/world/*</url-pattern>
</servlet-mapping>

</web-app> Standard URL filtering
April 05 Prof. Ismael H. F. Santos - [email protected] 35

Aplicação Básica - Web.xml


„ ${webapp}\WEB-INF\web.xml
web.xml: 1.Servlet que despacha requisições para as
<web-app> implementações dos Controles registrados
… 2.Cada servlet tem o seu proprio contexto (default
<servlet> definido em "{servlet-name}-servlet.xml“)
<servlet-name> springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup> Uma webapp pode ter qq
</servlet> numero desses servlets

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.html</url-pattern> 3. redireciona todo .html
</servlet-mapping> para servelt de dispacho

</web-app>
April 05 Prof. Ismael H. F. Santos - [email protected] 36

18
Aplicação Básica - Context Hierarchy

web.xml

ApplicationContext.xml

z ${servlet-name}-servlet.xml
From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet

April 05 Prof. Ismael H. F. Santos - [email protected] 37

Spring-MVC - Controllers

April 05 Prof. Ismael H. F. Santos - [email protected] 38

19
Spring-MVC - DispatcherServlet

April 05 Prof. Ismael H. F. Santos - [email protected] 39

Spring MVC – Execução (Run-time)

http://www.theserverside.com/tt/articles/article.tss?l=AjaxandSpring

April 05 Prof. Ismael H. F. Santos - [email protected] 40

20
Spring MVC Flow
„ DispatcherServlet
„ recebe requisições domeio externo (do navegador, por
exemplo) e comanda o fluxo de tarefas no Spring MVC;
„ HandlerMapping
„ dada uma requisição em URL, este componente irá
retornar o Controller que está associado a ela;
„ Controller
„ realiza comuniação entre o MVC do Spring com a
camada de negócio. Retorna um objeto ModelAndView;
„ ModelAndView
„ armazena os dadosretornados pela camada de negócio
para serem exibidos. Além disso, contêm um nome lógico
de uma determinada View
April 05 Prof. Ismael H. F. Santos - [email protected] 41

Spring MVC Flow


„ View
„ contêm informações de renderização para que o usuário possa ver
o que solicitou;
„ ViewResolver
„ a partir do nome lógico contido no objeto ModelAndView, este
componente determina a View que será exibida.
„ DispatcherServlet
„ Delega operações para
outros componentes;

„ web.xml -->

April 05 Prof. Ismael H. F. Santos - [email protected] 42

21
Spring MVC Flow – Pre Dispatcher

Dispatcher

Web.xml finds a
servlet (dispatcher)
mapped (and filtered)
to it.

April 05 Prof. Ismael H. F. Santos - [email protected] 43


From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet

Spring MVC Flow – Pre Dispatcher


16:19:22:408 - INFO - HttpServletBean - Initializing servlet 'dispatcher'
16:19:22:408 - INFO - FrameworkServlet - FrameworkServlet 'dispatcher': initialization started
16:19:22:423 - INFO - XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/report-
servlet.xml]
16:19:22:455 - INFO - AbstractRefreshableApplicationContext - Bean factory for application context [WebApplicationContext for
namespace 'report-servlet']: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans
[productStatusController,ProductStatusAsXMLView,urlMapping,viewResolver,messageSource]; parent:
org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [productManager,product1,product2,product3];
root of BeanFactory hierarchy
16:19:22:455 - INFO - AbstractApplicationContext - 5 beans defined in application context [WebApplicationContext for namespace
'report-servlet']
16:19:22:455 - INFO - AbstractApplicationContext - Using MessageSource
[org.springframework.context.support.ResourceBundleMessageSource: basenames=[spring2webexamples.bus.report.web.messages]]
16:19:22:455 - INFO - AbstractApplicationContext - Unable to locate ApplicationEventMulticaster with name
'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@45b199]
16:19:22:455 - INFO - UiApplicationContextUtils - Unable to locate ThemeSource with name 'themeSource': using default
[org.springframework.ui.context.support.DelegatingThemeSource@18ec669]
16:19:22:470 - INFO - DefaultListableBeanFactory - Pre-instantiating singletons in factory
… productStatusController,ProductStatusAsXMLView
16:19:22:517 - INFO - FrameworkServlet - Using context class [org.springframework.web.context.support.XmlWebApplicationContext]
for servlet 'report'
16:19:22:517 - INFO - DispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request
handling provided
16:19:22:517 - INFO - DispatcherServlet - Unable to locate LocaleResolver with name 'localeResolver': using default
[org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@ec459a]
16:19:22:517 - INFO - DispatcherServlet - Unable to locate ThemeResolver with name 'themeResolver': using default
[org.springframework.web.servlet.theme.FixedThemeResolver@1cd9466]
16:19:22:517 - INFO - DispatcherServlet - No HandlerAdapters found in servlet 'dispatcher': using default
16:19:22:517 - INFO - DispatcherServlet - Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using
default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@6a765]
16:19:22:517 - INFO - FrameworkServlet - FrameworkServlet 'dispatcher': initialization completed in 109 ms
16:19:22:517 - INFO - HttpServletBean - Servlet 'dispatcher' configured successfully
April 05 Prof. Ismael H. F. Santos - [email protected] 44

22
Spring MVC Flow – Dispatcher

Dispatcher

Handler Mapping are reviewed


as to which Controller is to be
invoked.
Any defined and implemented
HandlerInterceptor.preHandle() calls are
made.

April 05 Prof. Ismael H. F. Santos - [email protected] 45


From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet

Spring MVC Flow – Dispatcher

Dispatcher

${web-app}/WEB-INF/${servlet-name}-servlet.xml
<bean id="urlMapping"
class="org.springframework...SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.htm">productController</prop>
<prop key="/change.htm">priceIncreaseForm</prop>
</props>
</property>
</bean>

April 05 Prof. Ismael H. F. Santos - [email protected] 46

23
Handler Mappings
„ The process of Handler Mapping binds incoming web
requests to appropriate handlers that then resolve to a
Controller(s) (in most cases)
„ On inbound requests, the DispatcherServlet hands it over to the
handler mapping to come up with an appropriate
HandlerExecutionChain
„ Note: Handler Mappings apply from the base url-pattern
specified in the web.xml
„ By default, if no handler mapping can be found in the
context, the DispatcherServlet creates a
BeanNameUrlHandlerMapping for you
April 05 Prof. Ismael H. F. Santos - [email protected] 47

“Out of the box” HandlerMappings


„ Concrete Implementations
„ BeanNameUrlHandlerMapping
„ maps incoming HTTP requests to names of beans, defined in the
web application context
„ SimpleUrlHandlerMapping
„ Map Ant-style path matching (see org.springframework.util.PathMatcher)
to a Controller
„ CommonsPathMapHandlerMapping
„ use Commons Attributes to determine mapping
„ ControllerClassNameHandlerMapping
„ Most often, the out-of-the box implementations are
sufficient
April 05 Prof. Ismael H. F. Santos - [email protected] 48

24
“Out of the box” HandlerMappings
„ BeanNameUrlHandlerMapping;
„ procura por controladores cujo nome corresponde à
alguma porção de um nome URL de alguma requisição.
„ SimpleUrlHandlerMapping;
„ é que é muito mais versátil, pois ele permite que se
declare uma lista de associações url-controladores, e não
interfere na nomencaltura dos beans de controladores,
deixando-os mais claros.

April 05 Prof. Ismael H. F. Santos - [email protected] 49

Anecdote: Under the covers Mapping


Execution

April 05 Prof. Ismael H. F. Santos - [email protected] 50

25
Anecdote: Under the covers Mapping
Execution
How does HandlerExecutionChain
actually handle a mapping to a
Controller?

HttpRequestHandlerAdapter
SimpleControllerHandlerAdapter
SimpleServletHandlerAdapter
ThrowawayControllerHandlerAdapter

April 05 Prof. Ismael H. F. Santos - [email protected] 51

Spring-MVC
„ As you can see, all incoming HTTP requests from a web
browser are handled by Controllers. A controller, as the
name indicates, controls the view and model by facilitating
data exchange between them.
„ The key benefit of this approach is that the model can
worry only about the data and has no knowledge of the
view.
„ The view, on the other hand, has no knowledge of the
model and business logic and simply renders the data
passed to it (as a web page, in our case)
„ The MVC pattern also allows us to change the view without
having to change the model

April 05 Prof. Ismael H. F. Santos - [email protected] 52

26
Spring-MVC
„ The DispatcherServlet is an actual Servlet
„ Requests that you want the DispatcherServlet to handle
will have to be mapped using a URL mapping in the same
web.xml file.

April 05 Prof. Ismael H. F. Santos - [email protected] 53

Spring-MVC
„ Each DispatcherServlet has its own WebApplicationContext, which
inherits all the beans already defined in the root
WebApplicationContext. file named [servlet-name]-servlet.xml in the
WEB-INF directory

April 05 Prof. Ismael H. F. Santos - [email protected] 54

27
Spring-MVC
„ With the above servlet configuration in place, you will need to have
a file called '/WEB-INF/golfing-servlet.xml' in your application; this
file will contain all of your Spring Web MVC-specific components
(beans). The exact location of this configuration file can be
changed via a servlet initialization parameter (see below for
details).

April 05 Prof. Ismael H. F. Santos - [email protected] 55

Spring-MVC Controllers
„ Spring provides many types of controllers.
„ The controller type depends on the functionality you need. For
example, do your screens contain a form? Do you need
wizardlike functionality? Do you just want to redirect to a JSP
page and have no controller at all?

April 05 Prof. Ismael H. F. Santos - [email protected] 56

28
Spring-MVC Objects
„ Model & View
„ Many of the methods in the Controller related subclasses return a
org.springframework.web.servlet.ModelAndView object.This
object holds the model (as a java.util.Map object) and view name
and makes it possible to return both in one return value from a
method.

„ Command (Form Backing) Object


„ Spring uses the notion of a command object, which is a
JavaBean class that gets populated with the data from an HTML
form’s fields.
„ This same object is also passed to our validators for data
validation, and if the validations pass, it is passed to the
onSubmit method (in controller related classes) for processing of
valid data.

April 05 Prof. Ismael H. F. Santos - [email protected] 57

Spring-MVC
„ Validator
„ An optional class that can be invoked for validating form data for a
given command (form) controller. This validator class is a
concrete class that implements
org.springframework.validation.Validator interface.
„ One of the two methods required by this interface is the validate
method, which is passed a command object, as mentioned
previously, and an Errors object, which is used to return errors.
„ Another notable validation class is org.springframework.validation.
ValidationUtils, which provides methods for rejecting empty fields.
„ Spring Tag Library (spring-form.tld in spring.jar)
„ The spring bind tag library is simple yet powerful. It is typically
used in JSP files via the <spring:bind> tag, which essentially binds
HTML form fields to the command object.
April 05 Prof. Ismael H. F. Santos - [email protected] 58

29
Spring-MVC Configuration Concepts
„ DispatcherServlet
„ DispatcherServlet (part of the org.springframework.web.servlet
package) is the entry point to the world of Spring Web MVC.
„ Handler Mappings
„ You can map handlers for incoming HTTP requests in the Spring
application context file.These handlers are typically controllers that
are mapped to partial or complete URLs of incoming requests
„ The handler mappings can also contain optional interceptors,
which are invoked before and after the handler.

April 05 Prof. Ismael H. F. Santos - [email protected] 59

Spring-MVC
„ View Resolvers
„ Resolve view names to the actual views (enterhours to
enterhours.jsp, for example). InternalResourceViewResolver is a
class to resolve view names.
„ Installing the Spring Framework on a Servlet Container
„ Spring Framework can be downloaded from
http://springframework.org.

April 05 Prof. Ismael H. F. Santos - [email protected] 60

30
Use of Interceptors
„ Some HandlerMappings allow you to call an
interceptor before the controller
„ Useful for checking for session timeout, adding
things to the request/session
„ common services: security, traffic logging, and
perhaps front-end common data validation
„ Implement the HandlerInterceptor Interface
„ Simply wire your implemented Interceptors into the
HandlerMapping
„ Kind of like AOP, but for Controllers

April 05 Prof. Ismael H. F. Santos - [email protected] 61

Use of Interceptors

<bean id="urlMapping"
class="org.springframework...SimpleUrlHandlerMapping">
...
<property name="intercepters">
<list>
<bean class="...CustomHandlerIntercepter" />
</list>
</property>
</bean>
April 05 Prof. Ismael H. F. Santos - [email protected] 62

31
WebApp
SpringMVC
Controllers

April 05 Prof. Ismael H. F. Santos - [email protected] 63

Spring MVC Flow: Controller

Dispatcher

Controller is called.
Model objects collected (or
instantiated)
and a “View” is chosen.

From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet
April 05 Prof. Ismael H. F. Santos - [email protected] 64

32
MVC: Give me a “C”
„ Controllers…
„ Provide access to the application behavior which is typically
defined by a service interface
„ Controllers interpret input and transform said input into a
sensible model which will be represented for output by the view
„ The Controller in Spring is very abstract, allowing
different kinds of controllers for different use cases.
„ Out of the box Controllers existing to facilitate working
with User driven Forms, “command” models, execute
wizard-style logic, and more
„ Role your own Controllers:
„ Common data handling, control logic, etc.
http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html#mvc-controller
April 05 Prof. Ismael H. F. Santos - [email protected] 65

The Simple Controller Interface

http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/Controller.html
April 05 Prof. Ismael H. F. Santos - [email protected] 66

33
Spring-MVC Controllers
„ SimpleFormController, UrlFilenameViewController and
AbstractController are the most often used.

April 05 Prof. Ismael H. F. Santos - [email protected] 67

Spring-MVC Controllers
„ AbstractController
„ basic, knows about caching, turning on/off get/set/post/head
„ ParameterizableViewController
„ always go to the same view
„ UrlFileNameViewController
„ parses the URL to return a view (http://blah/foo.html -> foo)
„ SimpleFormController
„ for form handling, hooks for attaching commands, validator
„ AbstractWizardFormController
easy wizard controller
„
„ ServletWrappingController
„ delegates to a servlet
April 05 Prof. Ismael H. F. Santos - [email protected] 68

34
“Out of the box” Controllers
„ Infrastructure „ Specialized
„ AbstractController „ MultiActionController
„ Command Controllers „ ServletWrappingController
„AbstractCommandController„ Resource
„ BaseCommandController „ ParameterizableViewController
„ Form „ ServletForwardingController
„ SimpleFormController „ AbstractUrlViewController
„ AbstractFormController „ UrlFilenameViewController
„ AbstractWizardFormController
„ CancellableFormController

April 05 Prof. Ismael H. F. Santos - [email protected] 69

Spring-MVC Controllers

April 05 Prof. Ismael H. F. Santos - [email protected] 70

35
Annotation-driven Controllers

April 05 Prof. Ismael H. F. Santos - [email protected] 71

Example of Annotated MVC


Controller

April 05 Prof. Ismael H. F. Santos - [email protected] 72

36
Creating a Basic Controller

April 05 Prof. Ismael H. F. Santos - [email protected] 73

Handling Forms
„ Set the Command (just a bean)
„ Set a Validator if needed (extend
org.springframework.validation.Validator)
„ Set destination views (form, success, failure, error)
„ By default, uses GET/POST to determine whether it
needs to load the form or process it

April 05 Prof. Ismael H. F. Santos - [email protected] 74

37
WebApp
SpringMVC
View

April 05 Prof. Ismael H. F. Santos - [email protected] 75

Spring MVC Flow: View Resolving

Dispatcher

Any defined and implemented


HandlerInterceptor.postHandle()
calls are made.
ViewResolver finds the
configured view.

From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet
April 05 Prof. Ismael H. F. Santos - [email protected] 76

38
View Resolving
„ If the ModelAndView suppplied to the Dispatcher from a
Controller requires resolution (the isReference() method
is true), the a ViewResolver has the responsibility for
finding a view matching the configured names
„ 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 ViewResolver

April 05 Prof. Ismael H. F. Santos - [email protected] 77

View Resolver
„ O ViewResolver obtém o View a ser usado pelo
aplicativo através da referência passada pelo objeto
ModelAndView, que por sua vez foi retornado por algum
Controller;
„ Tipos de ViewResolver
„ InternalResourceViewResolver;
„ BeanNameViewResolver;
„ ResourceBundleViewResolver;
„ XmlViewResolver;

April 05 Prof. Ismael H. F. Santos - [email protected] 78

39
View Resolving: Implementation
Classes
InternalResourceViewResolver A convenience subclass of UrlBasedViewResolver that supports InternalResourceView (i.e.
Servlets and JSPs), and subclasses such as JstlView and TilesView. The view class for all views
generated by this resolver can be specified via setViewClass(..). See the Javadocs for the
UrlBasedViewResolver class for details.

BeanNameViewResolver Simple implementation of ViewResolver that interprets a view name as bean name in the current
application context, i.e. in the XML file of the executing DispatcherServlet. This resolver can be
handy for small applications, keeping all definitions ranging from controllers to views in the
same place.

UrlBasedViewResolver A simple implementation of the ViewResolver interface that effects the direct resolution of
symbolic view names to URLs, without an explicit mapping definition. This is appropriate if your
symbolic names match the names of your view resources in a straightforward manner, without
the need for arbitrary mappings.

ResourceBundleViewResolver An implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified


by the bundle basename. The bundle is typically defined in a properties file, located in the
classpath. The default file name is views.properties.

XmlViewResolver An implementation of ViewResolver that accepts a configuration file written in XML with the
same DTD as Spring's XML bean factories. The default configuration file is /WEB-INF/views.xml.

AbstractCachingViewResolver An abstract view resolver which takes care of caching views. Often views need preparation
before they can be used, extending this view resolver provides caching of views.

VelocityViewResolver / A convenience subclass of UrlBasedViewResolver that supports VelocityView (i.e. Velocity


FreeMarkerViewResolver templates) or FreeMarkerView respectively and custom subclasses of them.

April 05 Prof. Ismael H. F. Santos - [email protected] 79


From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet

Different Views
„ Plenty of Views are packaged with Spring MVC:
„ JstlView
„ map to a JSP page
„ RedirectView
„ Perform an HTTP Redirect
„ TilesView, TilesJstlView
„ integration with tiles
„ VelocityLayoutView, VelocityToolboxView, VelocityView
„ Integration with the Velocity templating tool
„ FreeMarkerView
„ use the FreeMarker templating tool
„ JasperReportsView, JasperReportsMultiFormatView,
JasperReportsMultiFormatView, JasperReportsPdfView,
JasperReportsXlsView
„ Support for Jasper Reports

April 05 Prof. Ismael H. F. Santos - [email protected] 80

40
Creating a View with JSP and JSTL

April 05 Prof. Ismael H. F. Santos - [email protected] 81

WebApp
SpringMVC
Configuration

April 05 Prof. Ismael H. F. Santos - [email protected] 82

41
Configuring DispatcherServlet

April 05 Prof. Ismael H. F. Santos - [email protected] 83

Configuring ContextLoaderListener

April 05 Prof. Ismael H. F. Santos - [email protected] 84

42
Mapping URLs to Controllers

April 05 Prof. Ismael H. F. Santos - [email protected] 85

Configure a HandlerMapping

April 05 Prof. Ismael H. F. Santos - [email protected] 86

43
Configuring the ViewResolver

April 05 Prof. Ismael H. F. Santos - [email protected] 87

Spring MVC Flow: View Routing


${web-app}/WEB-INF/${servlet-name}-servlet.xml
<beans>
<!-- View Resolvers:
Note: view resolvers are searched in ORDER -->
Dispatcher
<bean id="viewResolverJstl"
class="org.springframework...InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
...
<bean id="viewResolverBeanName"
class="org.springframework...BeanNameViewResolver" />
</beans>
April 05 Prof. Ismael H. F. Santos - [email protected] 88

44
Anecdote: View Routing Search Order
...
// Did the handler return a view to render?
if (mv != null && !mv.wasCleared()) { 1
render(mv, processedRequest, response);
} –DispatchController
else {
protected void render(ModelAndView mv, HttpServletRequest request,
//... assume HandlerAdapter completed HttpServletResponse response) throws Exception {
}
... // Determine locale for request and apply it to the response.
Locale locale = this.localeResolver.resolveLocale(request);

–DispatchController.doDispatch()
response.setLocale(locale);

View view = null;


2
protected View resolveViewName(String viewName, // Do we need view name translation?
Map model, if (!mv.hasView()) {
Locale locale, mv.setViewName(getDefaultViewName(request));
HttpServletRequest request) }
throws Exception {
for (Iterator it = this.viewResolvers.iterator(); if (mv.isReference()) {
it.hasNext();) { // We need to resolve the view name.
ViewResolver viewResolver = view = resolveViewName(mv.getViewName(), mv.getModelInternal(),
(ViewResolver) it.next(); locale, request);
View view = viewResolver.resolveViewName(viewName, if (view == null) {
locale); throw new ServletException("Could not resolve view... ");
if (view != null) { }
return view; }
} else {
}
return null; 3 // No need to lookup: the ModelAndView object contains the
// actual View object.
view = mv.getView();
}
if (view == null) {
throw new ServletException("ModelAndView ... neither contains a view
–DispatchController name nor a View object in Servlet... ");
}
}

//debug msgs
April 05 Prof. Ismael view.render(mv.getModelInternal(),
H. F. Santos - [email protected], response); 89
}

Anecdote: View Routing Search Order


„ From Spring 2 Reference Document 13.5.2:
„ “Chaining ViewResolvers: the contract of a view
resolver mentions that a view resolver can return
null to indicate the view could not be found. Not all
view resolvers do this however!
„ … Check the Javadoc for the view resolver to see
if you're dealing with a view resolver that does not
report non-existing views.”

April 05 Prof. Ismael H. F. Santos - [email protected] 90

45
Spring MVC Flow: View

Dispatcher

Based on your ViewResolver


configuration, your view is
called.

From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet
April 05 Prof. Ismael H. F. Santos - [email protected] 91

Spring MVC Flow: View


Technology Typical View Implementations
JSP & JSTL …web.servlet.view.InternalResourceView
…web.servlet.view.JstlView
Tiles (Struts) …web.servlet.view.tiles.TilesConfigurer

Velocity & …web.servlet.view.velocity.VelocityViewResolver


FreeMarker …web.servlet.view.freemarker.FreeMarkerConfigurer
XSLT Inherit …view.xslt.AbstractXsltView

Documents Inherit …view.document.AbstractPdfView


(PDF/Excel) Inherit …view.document.AbstractJExcelView
JasperReports JasperReportsCsvView, JasperReportsHtmlView,
JasperReportsPdfView, JasperReportsXlsView,
JasperReportsMultiFormatView

Custom Implementations
April 05 Prof. Ismael H. F. Santos - [email protected] 92

46
Spring MVC Flow: View

Dispatcher

Any defined and implemented


HandlerInterceptor.
afterCompletion() calls are made.
Your view data is response is
returned to the caller

April 05 Prof. Ismael H. F. Santos - [email protected] 93

Spring MVC Run-time Flow


Web.xml finds Handler Mapping to Controller
dispatcher (HandlerInterceptor.preHandle() calls)

2
1 Dispatcher 3

4 Controller, Model
collected,“View” chosen.
6

(HandlerInterceptor.postHandle())
ViewResolver calls view

HandlerInterceptor. 5
afterCompletion(), View called
Data returned
April 05 Prof. Ismael H. F. Santos - [email protected] 94
From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet

47
JSTL Introduction: What is it?
„ What is JSTL?
„ JavaServer Pages Standard Tag Library, JSR 52.
„ JSTL provides an effective way to embed logic within
a JSP page without using embedded Java code
directly.
„ Goal
„ Provide the tags to the web page authors, so that
they can easily access and manipulate the
application data without using the scriptlets (java
code).

April 05 Prof. Ismael H. F. Santos - [email protected] 95


http://www.roseindia.net/jstl/jstl.shtml

JSTL Introduction: What is it?


„ Other facts
„ JSP tags are xml like tags, which can be used by
non-programmers (page authors or designers)
without knowledge of Java programming.
„ Because JSTL tags are xml, they fit nicely into an
XHTML strategy allowing web pages have greater
tool vender support (for validation and dynamic
data insertion) among other beneficial attributes
(such as schema support).
„ Bean driven (for data setting/access)
April 05 Prof. Ismael H. F. Santos - [email protected] 96
http://www.roseindia.net/jstl/jstl.shtml

48
JSTL Introduction: Concepts

„ Tag Library
„ Xml compliant structures performing JSP features without
knowledge of Java programming.
„ Concepts such as flow control (if, for each) and more…
„ Tags are extendable
„ Expression Language
„ Allows former java Scriptlet logic to be simplified into
expressions
„ Expression functions are extendable

April 05 Prof. Ismael H. F. Santos - [email protected] 97

JSTL Introduction: Before / After


„ old
<% For (Enumeration e = cart.getProducts();
e.hasMoreElements();) {
Product thisProduct = (Product)e.nextElement();
%>
<br />
<%=thisProduct.getDescription()%>
<% } %>

„ new
<c:forEach var="thisProduct" items="${cart.products}">
<br />
<p>${thisProduct.description}</p>
</c:forEach>
April 05 Prof. Ismael H. F. Santos - [email protected] 98

49
JSTL Introduction: EL Expressions
EL Expression Result
${1 > (4/2)} false
${4.0 >= 3} true
${100.0 == 100} true
${(10*10) ne 100} false
${'a' < 'b'} true
${'hip' gt 'hit'} false
${4 > 3} true
${1.2E4 + 1.4} 12001.4
${3 div 4} 0.75
${10 mod 4} 2
${empty param.Add} True if the request parameter named Add is null or an empty string

${pageContext.request.contextPath} The context path


The value of the numberOfItems property of the session-scoped
${sessionScope.cart.numberOfItems} attribute named cart
${param['mycom.productId']} The value of the request parameter named mycom.productId

${header["host"]} The host


${departments[deptName]} The value of the entry named deptName in the departments map

${requestScope['javax.servlet. The value of the request-scoped attribute named javax.servlet.


forward.servlet_path']} forward.servlet_path

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html#wp77083
April 05 Prof. Ismael H. F. Santos - [email protected] 99

JSTL Introduction: Other Resources

„ http://www.sitepoint.com/print/java-standard-
tag-library
„ http://java.sun.com/j2ee/1.4/docs/tutorial/doc/J
STL4.html
„ http://en.wikipedia.org/wiki/JSTL
„ http://www.roseindia.net/jstl/jstl.shtml
„ … lots more! (one word: Google)

April 05 Prof. Ismael H. F. Santos - [email protected] 100

50
Spring TagLib: Using JSTL

Note: Any Number of view


technologies can be utilized here.
http://www.theserverside.com/tt/articles/article.tss?l=AjaxandSpring

April 05 Prof. Ismael H. F. Santos - [email protected] 101

“Templating” using Spring & JSTL


1 Controller 4
Objects
Model
View
2 3

End
End User
User
Model to HTML Binding [HTML] Form to Object
Binding
April 05 Prof. Ismael H. F. Santos - [email protected] 102

51
Model to HTML Binding
...
public class ProductController implements Controller {
private final static String DEFAULT_VIEW = "hello";
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String now = (new java.util.Date()).toString();
...
logger.info("returning hello view with " + now);
<html xmlns="http://www.w3.org/1999/xhtml" ...> Map<String, Object> myModel = new HashMap<String, Object>();
... myModel.put(NOW_KEY, now);
<div id="products">
myModel.put(PRODUCTS_MGR_KEY,
<table>
getProductManager().getProducts());
<tr class="TableHeadingColor">
return new ModelAndView(DEFAULT_VIEW, "model", myModel);
<td class="TableHeadingColor">
<fmt:message key="productHeading" /> }
</td> }
<td><fmt:message key="priceHeading" /></td> ...
</tr>
1
<c:set var="count" value="0"></c:set>
<c:forEach items="${model.products}" var="prod">
<tr>
Controller
<td>
<div id="productCount-${count}">${prod.description}</div>
</td> Objects
<td>
<div id="priceCount-${count}">$ ${prod.price}</div>
</td>
</tr>
Model
<c:set var="count" value="${count + 1}"></c:set>
</c:forEach> 2
</table>
</div> View
...
</body> April 05 Prof. Ismael H. F. Santos - [email protected] 103
</html>

String Externalization in JSTL


„ I18N functionality in JSTL is provided by the “fmt” tag
„ Locale and resource bundles
<fmt:setlocale> <fmt:message>
<fmt:bundle> <fmt:param>
<fmt:setBundle> <fmt:requestEncoding>

„ Formatting for numbers, dates, and currency


<fmt:timeZone> <fmt:parseNumber>
<fmt:setTimezone> <fmt:formatDate>
<fmt:formatNumber> <fmt:parseDate>

http://www.javaranch.com/newsletter/200309/AnIntroductionToJstl.html

April 05 Prof. Ismael H. F. Santos - [email protected] 104

52
String Externalization in JSTL
„ Spring enhances these I18N support tags with it’s
own <Spring:message> tag
„ MessageSource integrated with Spring context
„ Define where your messages are stored
„ Works with the locale support that comes with Spring
„ Spring gives more flexibility in how the locale for
messages is resolved… fmt:message tag uses
request.getLocale() to establish the locale for
messages
http://forum.springframework.org/archive/index.php/t-10454.html

April 05 Prof. Ismael H. F. Santos - [email protected] 105

Form to Object Binding


SomeBean bean =
4 (SomeBean) command;
3

Controller
2 Class SomeBean{
Object public String getMyBeanFieldName();
public void setMyBeanFieldName(String);
Model
}
View <form:form name="myBeanForm" commandName="myCommand">
1 ...
<!—This is a Getter/Setter -->
<form:textarea path="myBeanFieldName" />
...
<input type="submit" value="Submit" />
</form:form>

April 05 Prof. Ismael H. F. Santos - [email protected] 106

53
Spring TagLib
„ Starting in Spring 2, a standard JSTL Tag Library was
added to help simplify form-based web pages
„ form
„ input z option
„ checkbox z options
„ radiobox z textarea
„ password
z hidden
„ select
z errors

April 05 Prof. Ismael H. F. Santos - [email protected] 107

Spring TagLib: Binding Forms


Sample JSP
<form:form name="regexpTestForm" commandName="regexpTest">
<table width="600" bgcolor="f8f8ff" border="0" cellspacing="0"
cellpadding="5">
<tr>
<td align="left" width="20">Regular Expression:</td>
<td align="left" width="580"><form:textarea path="regexp"
rows="4" cols="100" title="${msgregexpTitle}" /></td>
<td><form:errors path="regexp" /></td>
</tr>
<tr>
<td align="left" width="20">Sample Data:</td> <!-- Controllers -->
<bean id="regexpTesterForm"
<td align="left" width="580"><form:textarea path="testData"
rows="10" cols="100" title="test me" /></td>class="...my*FormControllerImp">
<td><form:errors path="testData" /></td> ...
</tr> <property name="commandName">
<value>regexpTest</value>
<tr>
</property>
<td colspan="2" align="center" width="100"> <property name="commandClass">
<div><input type="submit" align="middle" <value>MyBean</value>
value="Test Regexp and Sample Data" /></div>
</property>
</td> <property name="formView">
</tr> <value>regexpTester</value>
</table> </property>
</form:form> <property name="successView">
<value>regexpTester</value>
http://forum.springframework.org/showthread.php?p=120100
April 05
</property>
Prof. Ismael H. F. Santos - [email protected]
... 108
</bean> –Sample *-servlet.xml

54
Form Error Handling
„ Built-in workflow for form error management
„ Servers side Validator(s)
„ Identifiers errors at a “field” level

„ Leverages Message keys for Locale support

„ JSTL tags
„ <spring:hasBindErrors name=“commandObjName">

„ <form:errors path=“myBeanFieldName" />

April 05 Prof. Ismael H. F. Santos - [email protected] 109

Form Error Handling


public class RegexpValidator implements Validator {
...
…messages.properties
public void validate(Object obj, Errors errors) {
RegexpTestData regexpTestData = (RegexpTestData) obj;
... error.invalidRegexp=some msg
try {
// looking for errors
Pattern.compile(regexpTestData.getRegexp());
<!-- Controllers -->
}
catch (PatternSyntaxException e) { <bean id="regexpTesterForm"
errors.rejectValue("regexp", "error.invalidRegexp", new Object[] { class="...my*FormControllerImp">
regexpTestData.getRegexp(), e.getDescription() ...
}, "Invalid Regular Expression"); <property name="commandName">
return; <value>regexpTest</value>
} Sample Validator </property>
} <property name="commandClass">
} <value>MyBean</value>
... </property>
<tr> <property name="validator">
<td align="left" width="20">${msgregexpLabel}</td> <bean ... name=" RegexpValidator" />
<td align="left" width="580"> </property>
<form:textarea path="regexp"title="${msgregexpLabelDescription}" /> <property name="formView">
</td> <value>regexpTester</value>
<td width="800"> </property>
<p class="errorText"><form:errors path="regexp" /></p> <property name="successView">
</td> <value>regexpTester</value>
</tr> </property>
... ...
<spring:hasBindErrors name="regexpTest"> </bean>
<tr>
...
<td class="errorText">
<!-- Messages Sources -->
<spring:message code="fixAllErrors" text="???fixAllErrors???" />
</td> <bean id="messageSource"
</tr> class="org... MessageSource">
</spring:hasBindErrors> <property name="basename">
... Sample JSP <value>...messages</value>
</property>
April 05 ... Sample *-servlet.xml
Prof. Ismael H. F. Santos - [email protected] 110

55
Themes and Localization
„ Themes
„ a collection of static resources affecting the visual style
of the application, typically style sheets and images.
„ Localization
„ DispatcherServlet enables you to automatically resolve
messages using the client's locale via the
LocaleResolver

http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html#mvc-localeresolver
http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html#mvc-themeresolver

April 05 Prof. Ismael H. F. Santos - [email protected] 111

Theme and Locale: Resolver and


Intercepter
Class Description
Selects a fixed theme/locale, set using the
Fixed*Resolver
"default[Theme|Locale]Name" property.
The theme/locale is maintained in the users HTTP
Session*Resolver session. It only needs to be set once for each
session, but is not persisted between sessions.
The selected theme/locale is stored in a cookie on
Cookie*Resolver
the user-agent's machine.
<bean id="themeChangeInterceptor"
class="org...ThemeChangeInterceptor" >
<property name="paramName“name=“theme“ >
</bean>
<bean id="localeChangeIntercepter"
class="org... LocaleChangeInterceptor" >
<property name="paramName“name=“locale“ >
</bean>

http://.../test.htm?theme=mello-yellow&locale=en_US
April 05 Prof. Ismael H. F. Santos - [email protected] 112

56
Theme Management Configuration
${web-app}/WEB-INF/${servlet-name}-servlet.xml
...
<!-- Handler Mappings -->
<bean id="urlMapping"
class="org.springframework...SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="regexpTester.htm">regexpTesterForm</prop>
</props>
</property>
<property name="interceptors">
<list>
<ref local="themeChangeInterceptor" />
</list>
</property>
</bean>
...
<!-- Theme definitions -->
<bean id="themeResolver"
class="org.springframework...theme.SessionThemeResolver">
<property name="defaultThemeName" value="mello-yellow" />
</bean>
<bean id="themeChangeInterceptor"
class="org.springframework...theme.ThemeChangeInterceptor" />
</bean>
...April 05 Prof. Ismael H. F. Santos - [email protected] 113

FIM
April 05 Prof. Ismael H. F. Santos - [email protected] 114

57
Java Server Faces
„ JSR 127 – padrão oficial (27/05/2004);
„ Várias implementações;
„ Garantia de continuidade.
„ Similar aos frameworks MVC;
„ Foco no desenvolvedor:
„ Projetado para ser utilizado por IDEs;
„ Componentes UI extensíveis;
„ Tratamento de eventos (como no Swing!);
„ Suporte à navegação simples.

April 05 Prof. Ismael H. F. Santos - [email protected] 115

Ciclo de Vida de uma aplicação JSF

April 05 Prof. Ismael H. F. Santos - [email protected] 116

58

Você também pode gostar