Anotações
Apresentação de slides
Estrutura de tópicos
1
Modulo II
Spring-MVC
  • 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
  • Spring in the Web Tier
  • Spring in the Middle Tier
  • Spring-MVC
4
WebApp
5
Histórico Programação Web
6
Histórico Programação Web
7
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.
8
Servlet Container
9
Java Server Pages
10
Servlet Controller
11
“Separation of concerns”
12
Model-View-Controller (MVC) Design Pattern
  • 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
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

14
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.

15
Front Controller (Servlet Controller)
16
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

17
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.
18
WebApp
19
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.


20
Proposed Web App Layering
21
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/
22
Where Spring Framework Fits Into a JEE Architecture
23
Web App – Scenario 1
24
Web App – Scenario 2
25
Web App – Scenario 3
26
Web App – Scenario 4
27
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
28
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.
29
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


30
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
31
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>
32
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
33
WebApp
34
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
35
Aplicação Básica - Web.xml
  • ${webapp}\WEB-INF\web.xml
36
Aplicação Básica - Web.xml
  • ${webapp}\WEB-INF\web.xml
37
Aplicação Básica - Context Hierarchy
38
Spring-MVC - Controllers
39
Spring-MVC - DispatcherServlet
40
Spring MVC – Execução (Run-time)
41
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
42
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  -->



43
Spring MVC Flow – Pre Dispatcher
44
Spring MVC Flow – Pre Dispatcher
45
Spring MVC Flow – Dispatcher
46
Spring MVC Flow – Dispatcher
47
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
48
“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
49
“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.
50
Anecdote: Under the covers Mapping Execution
51
Anecdote: Under the covers Mapping Execution
52
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
53
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.


54
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




55
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).


56
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?
57
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.
58
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.
59
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.
60
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.


61
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
62
Use of Interceptors
63
WebApp
64
Spring MVC Flow: Controller
65
MVC: Give me a “C”
66
The Simple Controller Interface
67
Spring-MVC Controllers
  • SimpleFormController, UrlFilenameViewController and AbstractController are the most often used.


68
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
69
“Out of the box” Controllers
  • Infrastructure
    • AbstractController
  • Command Controllers
    • AbstractCommandController
    • BaseCommandController
  • Form
    • SimpleFormController
    • AbstractFormController
    • AbstractWizardFormController
    • CancellableFormController
  • Specialized
    • MultiActionController
    • ServletWrappingController
  • Resource
    • ParameterizableViewController
    • ServletForwardingController
    • AbstractUrlViewController
    • UrlFilenameViewController

70
Spring-MVC Controllers
71
Annotation-driven Controllers
72
Example of Annotated MVC Controller
73
Creating a Basic Controller
74
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


75
WebApp
76
Spring MVC Flow: View Resolving
77
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
78
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;

79
View Resolving: Implementation Classes
80
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
81
Creating a View with JSP and JSTL
82
WebApp
83
Configuring DispatcherServlet
84
Configuring ContextLoaderListener
85
Mapping URLs to Controllers
86
Configure a HandlerMapping
87
Configuring the ViewResolver
88
Spring MVC Flow: View Routing
89
Anecdote: View Routing Search Order
90
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.”
91
Spring MVC Flow: View
92
Spring MVC Flow: View
93
Spring MVC Flow: View
94
Spring MVC Run-time Flow
95
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).
96
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)
97
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
98
JSTL Introduction: Before / After
  • old
99
JSTL Introduction: EL Expressions
100
JSTL Introduction: Other Resources
  • 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
Spring TagLib: Using JSTL
102
“Templating” using Spring & JSTL
103
Model to HTML Binding
104
String Externalization in JSTL
  • I18N functionality in JSTL is provided by the “fmt” tag
    • Locale and resource bundles





    • Formatting for numbers, dates, and currency




105
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
106
Form to Object Binding
107
Spring TagLib
  • 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
Spring TagLib: Binding Forms
109
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" />
110
Form Error Handling
111
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
112
Theme and Locale: Resolver and Intercepter
113
Theme Management Configuration
114
"FIM"
  • FIM
115
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.
116
Ciclo de Vida de uma aplicação JSF