1
|
|
2
|
- Spring in Action
- Craig Walls and Ryan Breidenbach
- Professional Java Development with Spring
- Rod Johnson, Juergen Hoeller and Team
|
3
|
- Spring in the Web Tier
- Spring in the Middle Tier
- Spring-MVC
|
4
|
|
5
|
|
6
|
|
7
|
- 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.
|
8
|
|
9
|
|
10
|
|
11
|
|
12
|
- MVC
- Clearly separates business, navigation and presentation logic. It´s a
proven mechanism for building a thin, clean web-tier
- Model
- The domain-specific representation of the information on which the
application operates.
- View
- Renders the model into a form suitable for interaction, typically a
user interface element.
- Controller
- Processes and responds to events, typically user actions, and may
invoke changes on the model.
|
13
|
- 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
|
14
|
- 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.
|
15
|
|
16
|
- 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
|
17
|
- 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.
|
18
|
|
19
|
- 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.
|
20
|
|
21
|
- 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/
|
22
|
|
23
|
|
24
|
|
25
|
|
26
|
|
27
|
- 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
|
28
|
- 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.
|
29
|
- 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
|
30
|
- 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
|
31
|
- 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>
|
32
|
- 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
|
33
|
|
34
|
- 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
|
35
|
- ${webapp}\WEB-INF\web.xml
|
36
|
- ${webapp}\WEB-INF\web.xml
|
37
|
|
38
|
|
39
|
|
40
|
|
41
|
- 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
|
42
|
- 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 -->
|
43
|
|
44
|
|
45
|
|
46
|
|
47
|
- 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
|
48
|
- 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
|
49
|
- 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.
|
50
|
|
51
|
|
52
|
- 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
|
53
|
- 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.
|
54
|
- 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
|
55
|
- 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).
|
56
|
- 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?
|
57
|
- 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.
|
58
|
- 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.
|
59
|
- 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.
|
60
|
- 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.
|
61
|
- 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
|
62
|
|
63
|
|
64
|
|
65
|
|
66
|
|
67
|
- SimpleFormController, UrlFilenameViewController and AbstractController
are the most often used.
|
68
|
- 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
- ServletWrappingController
|
69
|
- Infrastructure
- Command Controllers
- AbstractCommandController
- BaseCommandController
- Form
- SimpleFormController
- AbstractFormController
- AbstractWizardFormController
- CancellableFormController
- Specialized
- MultiActionController
- ServletWrappingController
- Resource
- ParameterizableViewController
- ServletForwardingController
- AbstractUrlViewController
- UrlFilenameViewController
|
70
|
|
71
|
|
72
|
|
73
|
|
74
|
- 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
|
75
|
|
76
|
|
77
|
- 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
|
78
|
- 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;
|
79
|
|
80
|
- Plenty of Views are packaged with Spring MVC:
- JstlView
- RedirectView
- TilesView, TilesJstlView
- VelocityLayoutView, VelocityToolboxView, VelocityView
- Integration with the Velocity templating tool
- FreeMarkerView
- use the FreeMarker templating tool
- JasperReportsView, JasperReportsMultiFormatView,
JasperReportsMultiFormatView, JasperReportsPdfView,
JasperReportsXlsView
- Support for Jasper Reports
|
81
|
|
82
|
|
83
|
|
84
|
|
85
|
|
86
|
|
87
|
|
88
|
|
89
|
|
90
|
- 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.”
|
91
|
|
92
|
|
93
|
|
94
|
|
95
|
- 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).
|
96
|
- 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)
|
97
|
- 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
|
98
|
|
99
|
|
100
|
- http://www.sitepoint.com/print/java-standard-tag-library
- http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSTL4.html
- http://en.wikipedia.org/wiki/JSTL
- http://www.roseindia.net/jstl/jstl.shtml
- … lots more! (one word: Google)
|
101
|
|
102
|
|
103
|
|
104
|
- I18N functionality in JSTL is provided by the “fmt” tag
- Locale and resource bundles
- Formatting for numbers, dates, and currency
|
105
|
- 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
|
106
|
|
107
|
- Starting in Spring 2, a standard JSTL Tag Library was added to help
simplify form-based web pages
- form
- input
- checkbox
- radiobox
- password
- select
|
108
|
|
109
|
- 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" />
|
110
|
|
111
|
- 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
|
112
|
|
113
|
|
114
|
|
115
|
- 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.
|
116
|
|