Anotações
Apresentação de slides
Estrutura de tópicos
1
Modulo I
Frameworks Web
  • Prof. Ismael H F Santos


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

3
Ementa
  • Modelos MVC (Model View Controller) e MVC2
  • Application Layering
  • Comparação Frameworks Web


4
WebApp
5
Arquitetura MVC
  • Divide a aplicação em tres partes fundamentais
    • Model – Representa os dados da aplicação e as regras de negócio   (business logic)
    • View – Representa a informação recebida e enviada ao usuário
    • Controller – Recebe as informações da entrada e  controla o fluxo da aplicação
6
MVC original
  • O padrão de arquitetura MVC (model-view-controller) surgiu na comunidade smalltalk.
    • Criado por Trygve Reenskaug no fim dos anos 70
    • Usado no desenvolvimento de aplicações desktop por facilitar o desenvolvimento em camadas de aplicações que usam a orientação a objetos
7
MVC Next – Steve Jobs
  • A next (Steve Jobs), resolveu modificar esse modelo oferecendo uma alternativa para sua linguagem de programação objective-c.
    • Delega a responsabilidade de observar o modelo para a camada de Controller que, por sua vez, envia para a camada de visão as alterações ao invés da camada de View obter esses dados do Model.
8
MVC Model 2
  • Com o crescimento das aplicações web baseadas no protocolo HTTP que é sem estado, não temos mais uma sessão permanentemente aberta entre o cliente e o servidor. Além disso   o HTTP não prevê uma forma de “enviar” (push) informações do servidor para o cliente.


  • Isto impede o trabalho do Controller que não pode mais enviar informações para a View sem ser solicitado. Para contornar o problema a Sun criou o MVC Model 2, baseado no padrão FrontController.


  • Agora a camada Controller submete ações tentando acompanhar o processo de request-response do protocolo HTTP ao invés de observar a camada Model, criando um fluxo linear para a arquitetura das aplicações.
9
Padrão Front Controller
  • Padrão que consolida todas as requisições web em um único objeto manipulador, despachando o tratamento adequado dessas requisições conforme o comportamento esperado.









  • A seguir apresentamos mais detalhes do padrão
10
Implementação do MVC para Web
11
JSP Model I - Centrado em páginas
12
JSP Model II - Centrado em servlet
13
Como implementar ?
14
Pattern Command (GoF)
15
Pattern Command (GoF)
16
FrontController + Command
17
Exemplo de Implementação – hellojsp_2
18
Mapemamentos de comandos ou ações
19
Comandos ou ações (Service to Worker)
20
Data Access Objects (DAO)
21
Controlador (FrontController)
22
ValueBean ViewHelper (Model)
23
Pagina JSP (View) com custom tags
24
WebApp
25
Application Layering
  • A clear separation of application component responsibility.
    • Presentation layer
      • Concentrates on request/response actions
      • Handles UI rendering from a model.
      • Contains formatting logic and non-business related validation logic.
      • Handles exceptions thrown from other layers
    • Persistence layer
      • Used to communicate with a persistence store such as a relational DB
      • Provides a query language
      • Possible O/R mapping capabilities
        • JDBC, Hibernate, iBATIS, JDO, Entity Beans, etc.
    • Domain layer
      • Contains business objects that are used across above layers.
      • Contain complex relationships between other domain objects
      • May be rich in business logic
      • May have ORM mappings
      • Domain objects should only have dependencies on other domain objs
26
Application Layering (cont)
  • Where do we code business logic?
    • Domain objects
      • Heavy domain model / thin service layer approach
      • Business logic is embedded in domain objects
      • Takes advantage of OO programming
      • Behavior rich domain model
    • Service Layer
      • Thin domain model / heavy service layer approach
      • Wraps procedural business logic over domain objects
      • Anti-pattern according to Fowler – ‘Anemic Domain Model’
      • Provides a separation of business logic concerns from the domain model
      • Treats the domain model as ORM objects
27
Application Layering (cont)
  • More Architectural decisions…
    • How do we achieve independent layers of code that can provide clear separation, loose coupling, and allow communication with each other?
    • How can we design an architecture that can allow layer replacement without affecting existing layers?
    • What technologies, and frameworks, should be implemented in each layer?
    • How will we implement security?
    • Will the application be flexible to technology changes?
    • How will the application handle enterprise level services such as transactions, security, logging, resource pooling, profiling, etc?
28
Application Layering (cont)
  • Service layer
    • Gateway to expose business logic to the outside world
    • Manages ‘container level services’ such as transactions, security, data access logic, and manipulates domain objects
    • Not well defined in many applications today or tightly coupled in an inappropriate layer.
29
Service Layer
30
More about the Service Layer
  • Often tightly coupled with other layers
    • Struts is not where you place business logic and persistence logic!
  • The missing link IMHO in most applications today.
  • EJB – SLSB, SFSB provide the common J2EE business layer enterprise solutions for transactions within a container.  What about POJO?
  • Hand code transaction logic with JTA
  • Frameworks – Spring, Picocontainer, HiveMind, etc.
  • Lighterweight containers use
    • IoC/Dependency Injection
    • AOP
31
Real World EJB Usage
  • Stateless Session Beans (SLSBs)
    • One of the easiest beans to program, but still want to program with POJOs.
    • Local interfaces alleviate remote interface performance issues.
    • Used as facades to other objects
    • Allows developers to provide declarative transaction management.
  • Message Driven Beans (MDBs)
    • Easy to program
    • Provides asynchronous messaging
  • Distributed Transaction Management
  • RMI Remoting
  • How do we get the benefits of EJB without using an EJB container?
32
Proposed Web App Layering
33
More Application Layering Combinations
  • Presentation/Business/Persistence
    • Struts+Spring+Hibernate
    • Struts + Spring + EJB
    • JavaServer Faces + Spring + iBATIS
    • Spring + Spring + JDO
    • Flex + Spring + Hibernate
    • Struts + Spring + JDBC
  • You decide…
34
WebApp
35
Comparação entre Framewoks Web
  • Struts - http://struts.apache.org
    • Pros:
      • The “Standard” - lots of Struts jobs
      • Lots of information and examples
      • HTML tag library is one of the best
    • Cons:
      • ActionForms - they’re a pain
      • Can’t unit test - StrutsTestCase only does integration
      • Mailing list volume is overwhelming

36
Comparação entre Framewoks Web
  • Spring MVC - http://www.springframework.org
    • Pros:
      • Lifecyle for overriding binding, validation, etc.
      • Integrates with many view options seamlessly: JSP/JSTL,Tiles, Velocity, FreeMarker, Excel, XSL, PDF
      • Inversion of Control makes it easy to test
    • Cons:
      • Not many using it
      • Requires writing lots of code in JSPs
      • Almost too flexible - no common parent Controller
37
Comparação entre Framewoks Web
  • WebWork - http://opensymphony.org/webwork
    • Pros:
      • Simple architecture - easy to extend
      • Tag Library is easy to customize - backed by Velocity
      • Interceptors are pretty slick
    • Cons:
      • Documentation only recently written, few examples
      • Client-side validation immature

38
Comparação entre Framewoks Web
  • Tapestry - http://jakarta.apache.org/tapestry
    • Pros:
      • Very productive once you learn it
      • Templates are HTML - great for designers
      • Healthy and smart user community
    • Cons:
      • Documentation very conceptual, rather than pragmatic
      • Steep learning curve - very few examples
      • Impossible to test - page classes are abstract
39
Comparação entre Framewoks Web
  • JSF - http://java.sun.com/j2ee/javaserverfaces & http://myfaces.org
    • Pros:
      • J2EE Standard - lots of demand and jobs
      • Fast and easy to develop with Rich Navigation framework
    • Cons:
      • Tag soup for JSPs
      • Immature technology - doesn’t come with everything
      • No single source for implementation
40
Controllers and Views
  • Struts:
    • UserAction extends DispatchAction
  • Spring MVC:
    • UserFormController extends SimpleFormController
  • WebWork:
    • UserAction extends ActionSupport
  • Tapestry:
    •  UserForm extends BasePage
  • JSF:
    • UserForm
41
List Screens
  • How easy is it to integrate a sortable/pageable list of data?
    • Struts, Spring MVC and WebWork
      • all use Tag Libraries like the Display Tag
    • Tapestry has a contrib:
      • Table component
    • JSF
      • has a dataTable with no sorting – have to write your own logic if you want it

42
Bookmarking and URLs
  • Using container-managed authentication (or other filterbased security systems) allow users to bookmark pages. They can click the bookmark, login and go directly to the page.
  • WebWork
    • has namespaces - makes it easy
  • Struts and Spring
    • allow full URL control
  • Tapestry
    • has ugly URLs - difficult to segment the app for different roles
  • JSF
    • does a POST for everything
43
Validation
  • Validation should be easy to configure, be robust on the client side and either provide good out of the box messages or allow you to easily customize them.
  • Struts and Spring MVC
    • use Commons Validator – a mature solution
  • WebWork
    • uses OGNL for powerful expressions - client-side support very new
  • Tapestry
    • has very robust validation - good messages without need to customize
  • JSF
    • ugly default messages, but easiest to configure
44
Testability
  • Struts
    • can use StrutsTestCase
  • Spring and WebWork
    • allow easy testing with mocks (i.e. EasyMock, jMock, Spring Mocks)
  • Tapestry
    • is impossible to test because page classes are abstract
  • JSF
    • page classes can be easily tested and actually look a lot like WebWork actions
45
Success Messages
  • The duplicate-post problem, what is it?
    • Easiest way to solve: redirect after POST
  • Struts
    • is the only framework that allows success messages to live through a redirect
  • Spring and WebWork
    • require custom solutions
  • Tapestry
    • requires you to throw an Exception to redirect
  • JSF
    • requires a custom solution, i18n messages difficult to get in page beans
46
Spring Integration
  • All frameworks have integration with Spring
  • Struts:
    • ContextLoaderPlugin and Base classes
  • WebWork:
    • SpringObjectFactory
  • Tapestry:
    • override base engine, grab from servlet context, put into global map
  • JSF:
    • DelegateVariableResolver or JSF-Spring Library

47
Internationalization
  • JSTL’s <fmt:message> tag makes it easy
  • No standard for getting i18n messages in controller classes
  • Struts, Spring and JSF
    • encourage one ResourceBundle per locale
  • WebWork and Tapestry
    • advocate separate files for each page/action

48
Page Decoration
  • Used Tiles since it first came out in 2001
  • SiteMesh is much easier to setup and use
  • Tiles can be used in:
    •  Struts, Spring and JSF
  • Requires configuration for each page
  • SiteMesh can be used with all frameworks
    • Requires very little maintenance after setup

49
Tools
  • Struts
    • has a lot of IDE support and even has frameworks built on top of it (i.e. Beehive’s PageFlow)
  • Spring
    • has Spring IDE, only does XML validation, not a UI/web tool
  • WebWork
    • has none
  • Tapestry
    • has Spindle - great for coders
  • JSF
    • has many, all cost money and hook into proprietary app servers