1 Spring MVC
1 Spring MVC
Spring-MVC
Bibliografia
Spring in Action
Craig Walls and Ryan Breidenbach
Professional Java Development with Spring
Rod Johnson, Juergen Hoeller and Team
1
Ementa
Spring in the Web Tier
Spring in the Middle Tier
Spring-MVC
WebApp
Histórico
Programação
Web
2
Histórico Programação Web
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.
Servlet Container
4
Java Server Pages
Servlet Controller
5
“Separation of concerns”
Páginas Web (JSP, HTML, etc.) cuidam da parte visual;
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
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
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
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.
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/
11
Web App – Scenario 1
12
Web App – Scenario 3
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
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
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>
getWebApplicationContext(servletContext).getBean(“beanName”)
16
WebApp
SpringMVC
application
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
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
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
Spring-MVC - Controllers
19
Spring-MVC - DispatcherServlet
http://www.theserverside.com/tt/articles/article.tss?l=AjaxandSpring
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
web.xml -->
21
Spring MVC Flow – Pre Dispatcher
Dispatcher
Web.xml finds a
servlet (dispatcher)
mapped (and filtered)
to it.
22
Spring MVC Flow – Dispatcher
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>
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
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.
25
Anecdote: Under the covers Mapping
Execution
How does HandlerExecutionChain
actually handle a mapping to a
Controller?
HttpRequestHandlerAdapter
SimpleControllerHandlerAdapter
SimpleServletHandlerAdapter
ThrowawayControllerHandlerAdapter
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
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.
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
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).
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?
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.
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.
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.
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
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
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
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.
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
Spring-MVC Controllers
35
Annotation-driven Controllers
36
Creating a Basic Controller
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
37
WebApp
SpringMVC
View
Dispatcher
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
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;
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.
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.
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
40
Creating a View with JSP and JSTL
WebApp
SpringMVC
Configuration
41
Configuring DispatcherServlet
Configuring ContextLoaderListener
42
Mapping URLs to Controllers
Configure a HandlerMapping
43
Configuring the ViewResolver
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);
//debug msgs
April 05 Prof. Ismael view.render(mv.getModelInternal(),
H. F. Santos - [email protected], response); 89
}
45
Spring MVC Flow: View
Dispatcher
From http://www.springframework.org/docs/reference/mvc.html#mvc-servlet
April 05 Prof. Ismael H. F. Santos - [email protected] 91
Custom Implementations
April 05 Prof. Ismael H. F. Santos - [email protected] 92
46
Spring MVC Flow: View
Dispatcher
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).
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
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
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html#wp77083
April 05 Prof. Ismael H. F. Santos - [email protected] 99
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)
50
Spring TagLib: Using JSTL
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>
http://www.javaranch.com/newsletter/200309/AnIntroductionToJstl.html
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
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>
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
54
Form Error Handling
Built-in workflow for form error management
Servers side Validator(s)
Identifiers errors at a “field” level
JSTL tags
<spring:hasBindErrors name=“commandObjName">
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
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.
58