Cours Spring MVC
Cours Spring MVC
Documentation http://static.springsource.org/spring/docs/current/spri htt // t ti i / i /d / t/ i ngframeworkreference/html/mvc.html Tutorial http://viralpatel.net/blogs/tutorialspring3mvc introductionspringmvcframework/ Download Springframework http://www.springsource.org/spring htt // i / i framework#download Utiliser3.1.3 313
Le cur de lenvironnement Spring est un conteneur lger Un conteneur lger sert contenir un ensemble dobjets instancis et initialiss, formant un contexte initial (ou une hirarchie de contextes) pour une application.
Ce contexte initial est souvent construit partir dune description externe (xml) ( l) d dcrivant i l les objets bj crer, l les valeurs l i initiales i i l et l les dpendances entre objets.
Les dpendances (liens) entre objets sont automatiquement cres partir de la description (on parle dinjection de dpendances) et non par les objets eux-mmes par programmation. Cest le Design g Pattern de lInversion du Contrle : IoC
Exemple simplifi: Avec les classes: class Personne { String nom; Voiture car; } class Voiture {String nom;}
et la description de contexte Spring: <beans> <bean id= =" user " class= =" Personne "> > <property name=" nom " value=" jean "/> <property name= " car " ref= "vehicule "/> </bean> <bean id=" vehicule " class=" Voiture "> <property name=" nom " value=" megane "/> </bean> </beans> Le contexte initial de lapplication l application dans le conteneur SPRING sera:
Personne user nom:jean j car: Voiture nom:megane vehicule
SpringMVC est un framework de prsentation, pour application WEB, suivant le modle MVC, et fond sur le conteneur lger de SPRING
Dans le cas de SpringMVC p g le conteneur va servir crer: -Le contexte de lapplication Web -Les objets traitant les requtes (Controller) -Les objets crant les pages HTML (View) -Les objets donnes des formulaires (Command) -Les liens avec les couches mtiers et BD -Et pleins dautres -Le mapping des URL vers les contrleurs -Le mapping des vues , etc. Linversion du contrle permet ensuite de changer le comportement de lapplication, en modifiant la description xml du conteneur, sans changer c a ge les es lments e sp programms! og a s
La vision de SpringMVC
La org.springframework.web.servlet.DispatcherServlet g p g p est le p point dentre gnrique qui dlgue les requtes des Controller Un org.springframework.web.servlet.mvc.Controller prend en charge une requte, et utilise la couche mtier pour y rpondre rpondre. Un Controller fabrique un modle sous la forme dune java.util.Map contenant les lments de la rponse. Un Controller C choisit une org.springframework.web.servlet.View f qui sera paramtre par la Map pour donner la page qui sera affiche.
Spring 3.x
ControllerSpring 3
Spring 3simplifielacrationdescontrleurs: annotations@Controller ll et@RequestMapping Pasdinterfaceimplmenter Lecontrleurlep plussimple: p uneclasseannot@Controller plusunemthodeannot@RequestMapping
URL
DispatcherServlet HandlerMapping
Choix dun contrleur en fonction de lURL
Metier
MonControleur
HttpServletRequest handleRequest ModelAndView =
ViewResolver
Page HTML
Vue
Model
fournit par Spring A fournir
ContrleurSpring 3
@Controller public class Affichage p g { @Controller Pas dinterface implmenter public Groupe getGroupe() { return groupe; } public void setGroupe(Groupe groupe) { this.groupe = groupe; }
Spring 3.x
// un groupe de personnes fourni par le contexte de l'application private Groupe groupe; Le groupe sera inject lors de la cration du contexte
// gestion de la requte @RequestMapping("/afficher") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Nom de la vue utiliser pour gnrer la page ModelAndView mav = new ModelAndView(); mav.setViewName("vuemembres"); mav.addObject("groupe", groupe); return mav; } Ajout Aj td du groupe au modle
<%@ page language="java" pageEncoding="ISO-8859-1" contentType="text/html;charset=ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Affichage</title> On retrouve </head> le modle <body> <h2>Groupe</h2> <table border="1"> <tr> <th colspan colspan="3" 3 align align="center" center >Membres du groupe</th> </tr> <tr> <c:forEach var="personne" items="${groupe.membres}"> <td>${personne}</td> </c:forEach> </tr> </table> <a href="<c:url value="/ajouter.html"/>">Ajout</a> </body> </html> Fi hi / Fichier /views/vuemembres.jsp i / b j
Ce fichier web.xml ne change jamais. C fi Ce fichier hi est td dans l le rpertoire t i WEB WEB-INF INF
Injection de dpendance
groupe: g p
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jee http://www.springframework.org/schema/jee xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Scan package to discover spring annotations --> <context:component-scan base-package="web"/> pourdcouvrir lesannotations
<beans> <!-- le controleur --> <bean id="AffichageController" class="web.Affichage"> < <property t name="groupe" " " ref="groupe"/> f " "/> </bean> Ladpendance <! linstance du metier <b <bean id id="groupe" " " class="metier.Groupe" l " ti G " <property name="membres"> <list> <value>Paul</value> < al e>Mlanie</ al e> <value>Mlanie</value> <value>Jacques</value> </list> </property> </bean> pourinjecterlegroupe
Exemple: 6 les mappings 1 - On veut que lURL /afficher.html dclenche notre contrleur daffichage.
Il faut le spcifier avec lannotation @RequestMapping (Spring 3.x) 2 - On veut que le nom vuemembres dsigne le fichier vuemembres.jsp
membres WEB-INF web.xml membres-servlet.xml e b es se e vues vuemembres.jsp j p src Lappli Web avec Spring: metier Groupe.java web Affichage.java lib spring.jar standard.jar jstl.jar commons-collections.jar ll ti j classes Lancement: http://localhost:8080/membres/afficher.html
<! un autre resolveur de vues --> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/vues/vues <value>/WEB INF/vues/vues.xml</value> xml</value> </property> </bean>
Fichier /WEB-INF/vues/vues.xml
<?xml version="1.0" encoding="ISO_8859-1"?> <!DOCTYPE beans SYSTEM "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="vuemembres" class="org.springframework.web.servlet.view.JstlView"> <property name="url"> <value>/WEB-INF/vues/vuemembres.jsp</value> </property> /p p y </bean> </beans>
On peut crer un contexte global lapplication l application web web, utile pour y mettre une fois pour toute la liaison avec la couche mtier. Il faut utiliser pour cela un fichier applicationContext.xml.
<!-- le chargeur du contexte de l'application --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> ...
</web-app>
membres mappings.properties WEB-INF web.xml membres-servlet.xml applicationContext.xml vues Lappli Web avec Spring: src metier Groupe.java web Affichage.java lib spring.jar spring jar standard.jar jstl.jar commons-collections commons collections.jar jar classes vues.xml vuemembres.jsp
Spring 3.x
Formulaire
Metenuvre: unepageweb b(ex: ( jsp) j ) uncontrleuravecjusquedeuxmthodespourtraiter lesrequtesget etpost unobjetcommand pourpasserlesdonnesentrele formulaireetlecontrleur Unemthodepourinitialiserlobjetcommand
Spring 3.x
GET Request
Cre ou retrouve
Formulaire prrempli
view formulaire
logicalview
POST data
Utilise @RequestMapping(method = RequestMethod.POST) protected String processPost()
Page HTML
Objet ModelAndView
Metier
Initialiserlobjet j deCommand
Parunemthodeannot@ModelAttribute
@ModelAttribute("commandAjout") publicuserInfoData initFormObject(HttpServletRequest HttpSer letRequest request){ CommandAjout command =newCommandAjout(); returncommand ; }
Oudanslamthodeduget
Spring 3.x
@Controller @RequestMapping("ajouter") public class AjoutController { private Groupe groupe; @Inject public void setGroupe(Groupe groupe) { this.groupe = groupe;} @RequestMapping(method q pp g = RequestMethod. q GET) protected Object processGet(ModelMap model) { // Create the command used to fill the jsp form CommandAjout cmd = new CommandAjout(); cmd.setNouveauMembre("Entrez un nom"); // Add it to the implicit model model.addAttribute("commandAjout", cmd); // return the logical name of the view used to render the form. return "formulaire"; }
Injecteunobjetdutypedemand
@RequestMapping(method = RequestMethod.POST) protected String processPost( @ModelAttribute("commandAjout") CommandAjout commandAjout, BindingResult result, SessionStatus status ) throws Exception p { if( result.hasErrors()) { lersultatdubind return "formulaire";} // Add new membre groupe.addMembre(commandAjout.getNouveauMembre()); status setComplete(); status.setComplete(); indiquelafindelasession return "confirmation"; nettoielesattributsdumodle } }
Spring 3.x
formulaire.jsp nomdelobjetdanslemodle <body><h3>Formulaire Ajouter un membre </h3> <form:form commandName="commandAjout"> <table> nomdepropriete danslobjet <tr> <td>Nouveau Membre</td> <td><form:input path="nouveauMembre" /></td> <%-- Show errors for name field --%> <td><form:errors path="nouveauMembre" /></td> </tr> <tr> <td colspan="3"><input type="submit" value="Envoyer" /></td> </tr> </table> </form:form> confirmation jsp confirmation.jsp
<body> <h3>Confirmation de l'ajout</h3> valeurdelaproprit <table border="1"> <tr> <td>Nouveau Membre </td> <td>${commandAjout.nouveauMembre}</td> </tr> </table> < href= <a h f "<c:url "< l value="/afficher.html"/>">Retour</a> l "/ ffi h ht l"/>">R t </ > </body>
Spring 3.x
Spcifielepackagescanner
membres mappings.properties WEB-INF web.xml membres-servlet.xml applicationContext xml applicationContext.xml vues vues.xml vuemembres.jsp formulaire.jsp confirmation.jsp src metier Groupe.java web AffichageControler.java AjoutControler.java CommandAjout.java lib spring.jar standard.jar jstl.jar commons-collections.jar classes
fichier index.jsp:
<%@ page language="java" pageEncoding="ISO-8859-1" contentType text/html;charset ISO 8859 1 %> contentType="text/html;charset=ISO-8859-1"%> <%@ taglib uri="/WEB-INF/c.tld" prefix="c" %> <c:redirect url="/afficher.html"/>
Et mettre des liens pour naviguer dans lapplication. - Dans vuesmembres.jsp, pour permettre dajouter des membres
<a href="<c:url value="/ajouter.html"/>">Ajout</a>
membres mappings.properties index.jsp WEB-INF web.xml membres-servlet.xml b l t l applicationContext.xml vues vues.xml vuemembres.jsp formulaire.jsp confirmation.jsp fi ti j src metier Groupe.java p j web Affichage.java Ajout.java C CommandAjout.java dAj t j lib spring.jar standard.jar j jstl.jar commons-collections.jar classes
Spring 3
Spring 3.x
Gestiondeserreurs
Leserreurspeuventtreissues: De D mauvaises i saisies i i dans d l lesformulaires f l i Dedonnessaisiesnonvalablespourlemtier Des D exceptions i remontantdu d mtier i Lesmauvaisessaisiespeuventtredtectspar: laconversiondelarequtehttp objetcommand desobjetsdevalidation
Spring 3.x
Erreurdeconversion
@RequestMapping(method = RequestMethod.POST) protected String onSubmit( @ModelAttribute("commandAjout") CommandAjout commandAjout, BindingResult result, result SessionStatus status ) throws Exception { if( result.hasErrors()) { return "formulaire"; }
retourneauformulaireencasderreurs
effacelasessionsiok
Spring 3.x
Validation
Doitsefaireexplicitement
@Controller @RequestMapping("ajouter") @RequestMapping( ajouter ) public class AjoutController { @Inject private ValidatePersonne validator;
Lobjetvalidator
@RequestMapping(method = RequestMethod.POST) protected String onSubmit( @ModelAttribute("commandAjout") @ModelAttribute( commandAjout ) CommandAjout commandAjout, commandAjout BindingResult result, SessionStatus status ) throws Exception { // validation validator validate(commandAjout result); validator.validate(commandAjout, if( result.hasErrors()) { return "formulaire"; appellavalidation.UtiliseleBindResult }
org.springframework.validation.Errors
Register a global error for the entire target object, using the given error description. Register a global error for the entire target object, using the given error description.
Spring 3.x
Validation
Peutaussiutiliserlestandard JSR303Validator V lid t Utiliseletag@Valid etdesvalidators Ncessite N i uneimplmentation i l i d dustandard d d
ex:Hibernate Validate
Nondveloppici
Commentafficherleserreursdans ( ) lesJSP?(vers>2.5)
EnutilisantuntagSpring :letag
Erreursencouleurs:dclarerunstyleetlutiliserdanslerreur
<html> ht l
<style> .error { color: #ff0000; } .errorblock{ errorblock{ color: #000; background-color: #ffEEEE; border: 3px solid #ff0000; padding:8px; margin:16px; } </style>
<body> <form:form commandName="commandAjout" acceptCharset="UTF-8">
L gestion La ti d des messages d derreurs Dans le fichier de configuration g il faut indiquer q q que lon va utiliser un fichier messages.properties pour contenir les messages.
<!-- le fichier des messages --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <value>messages</value> </property> </bean>
L gestion La ti d des messages d derreurs i18n i18 Il p peut y avoir un fichier de messages g p pour chaque q langue. g Suffixer le nom par le local et le country : fr_FR en_US de_DE Le framework choisit le fichier en fonction des prfrences utilisateur
<!-- le fichier des messages --> <b <bean id " id="messageSource" S " class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <value>messages</value> </property> </bean>
messages_fr_FR.properties commandAjout.nouveauMembre.necessaire=Un nom est ncessaire commandAjout.echec=Echec de l'ajout messages g _en_US.properties p p commandAjout.nouveauMembre.necessaire=Name is mandatory commandAjout.echec=Duplicate name
vues
vues.xml vuemembres.jsp formulaire.jsp confirmation.jsp metier Groupe.java web Affichage.java g j Ajout.java CommandAjout.java ValidatePersonne.java lib spring.jar standard.jar jstl.jar commons-collections.jar j classes messages.properties
AccderunobjetJNDIouEJB
Lobjetdoitexisterdansunautrecontainer Oninjectelebean ex:injecter j unbean dansSpring p g
membres-servlet.xml
<beans xmlns= xmlns="http://www http://www.springframework.org/schema/beans springframework org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www springframework org/schema/beans/spring-beans-2 5 xsd http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"> <bean id= id="catalogController" catalogController class= class="ipint ipint.mysite.CatalogController mysite CatalogController"> > <property name="catalog" ref="catalogId"/> injection </bean> <jee:jndi lookup id= <jee:jndi-lookup id="catalogId" catalogId jndi jndi-name="CatalogBean/remote" name= CatalogBean/remote cache="true" /> recherche du bean lien nom l ogique <-> nom JNDI </beans>
Accderunobjet j JNDIouEJB
<jee:jndi-lookup> <jee:jndi lookup>
Acces par JNDI
Documentation
Spring
http://www.springframework.org/
tutorial l
http://www.springframework.org/docs/MVCstepbystep/SpringMVCstepby
step.html
tutorial;aadapterpourladernireversion
article
http://www.theserverside.com/tt/articles/article.tss?l=IntrotoSpring25 synthese y deSpring p g
documentation
http://static.springframework.org/spring/docs/2.5.x/reference/index.html lareference pdf :(http://static.springframework.org/spring/docs/2.5.x/springreference.pdf)
Exemples
ExemplesfourniesavecSpring \spring \ i framework f k2.5.x\samples \ l
UtiliserSpring 3
Ncessitelesjars
(situsdansspring3.x/dist) ( p g3 / )
org.springframework.web.servlet org.springframework.web org.springframework.asm org.springframework.beans org.springframework.core org springframework core org.springframework.context org.springframework.expression
Download:
http://www.springsource.org/download
Partie2
La navigation dans une application MVC prcise comment les pages senchanent pour lutilisateur. La navigation peut tre construite: - laide du lien (href) dans les pages JSP lutilisateur passe dune page g une autre en cliquant sur le lien - laide de boutons de formulaires dans les pages JSP lutilisateur en cliquant sur le bouton dclenche une action dans le serveur, action qui retournera une autre page - laide de redirections du navigateur cest ici le serveur qui indique au navigateur lURL de poursuite Lutilisation simultane de ces trois mcanismes rend complexe lexpression de la navigation dans une application
Le modle Spring MVC essaie de simplifier cet aspect en permettant dexprimer la navigation uniquement dans les contrleurs et non dans les pages JSP JSP. Pour cela dans le modle Spring MVC, un formulaire est toujours envoy par un contrleur et retournera (une fois rempli par lutilisateur) toujours au contrleur qui la envoy. Cest le cas du SimpleFormController vu prcdemment:
Get
Lattribut action du formulaire nest pas prcis !
Formulaire
Submit
Formulaire.jsp: <form method = post > . <input type= Submit > </form>
Vue suivante
Get
Formulaire
Submit
Formulaire.jsp: <form f method th d = post t> . <input type= Submit > </form> /form
Vue suivante
La vue suivante peut tre une autre page JSP (JstlView) ou une redirection vers un autre contrleur (RedirectView)
Si la page suivante doit aussi contenir un formulaire alors il faut faire une redirection vers le contrleur qui va gnrer ce formulaire et va le recevoir en retour !!!
Exemple:
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/SaisieNom.html">SaisieNom</prop> key="/SaisieNom html">SaisieNom</prop> <prop key="/SaisiePrenom.html">SaisiePrenom</prop> </props> </property> </bean>
SaisieNom.html
Nom Submit
public class SaisieNom extends SimpleFormController { protected ModelAndView onSubmit() { return new ModelAndView("redirectionSaisiePrenom" ); } }
Redirection
vues.xml
Prnom Submit
Vue suivante
La squence des deux pages(pour lutilisateur) est programme dans le premier contrleur qui utilise une redirection vers le d deuxime i contrleur t l ( (et t non d dans une page JSP) !
Le contrleur MultiActionController Ce contrleur permet de grer une page complexe comprenant plusieurs boutons et/ou plusieurs sous pages.
(une action par bouton)
Action1
Action1 Action2
Methode Action 1
Methode Action 2
retour
Action3
Methode Action 3
suite
MultiActionControleur (Spring3) ( p g )
Classeannot
lURLglobale(surlaclasse)
@RequestMapping(method = RequestMethod.GET) public bli Map<String, M St i A Appointment> i t t get() t() { return appointmentBook.getAppointmentsForToday(); }
Autrevariante:
@RequestMapping(value="/new", R tM i ( l "/ " method th d = RequestMethod.GET) R tM th d GET) public AppointmentForm getNewForm() { return new AppointmentForm(); }
Onaccdeaucontrleurpar
http://serveur/appointement/new
Commentmapperunboutonsuruncontrleur? Rechercherdansdoc.
Spring 2 Un MultiActionController doit tre dclar dans le ficher <projet>-servlet.xml, ainsi que la manire de dterminer les actions excuter en fonction de lURL Exemple: ici le choix de laction se fera sur la prsence dun paramtre de la requte qui a le nom de lune des actions
<bean id="MonController" class="web.MonController"> <property name="methodNameResolver"> <ref local="MaMethodNameResolver"/> </property> </bean> <bean id="MaMethodNameResolver MaMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="defaultMethodName"><value>action1</value></property> <property name="methodParamNames"> <list> <value>action2</value> <value>action3</value> </list> </property> </bean>
Spring 2
package web; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class MonController extends MultiActionController { // action par dfaut: affichage page principale public ModelAndView action1(HttpServletRequest request, HttpServletResponse response) { return new ModelAndView( vuePagePrincipale ); } // action: affichage page secondaire public ModelAndView action2(HttpServletRequest request, request HttpServletResponse response) { return new ModelAndView( vuePageSecondaire ); } // action : traitement retour page secondaire public ModelAndView action3(HttpServletRequest request, HttpServletResponse response) { return new ModelAndView( suite ); }
Par exemple dans la page secondaire on aurait un formulaire avec un <input type="submit" name="action1" value="Retour" >
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD // // HTML 4.01 Transitional//EN" // "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; / charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form method="post"> <input type="submit" name="action1" value="Afficher"> <input type="submit" name="action2" value="Saisir"> <input type="submit" name="action3" value="Retour"> </form> /f </body> </html>
Liste slection des noms des personnes Voir Dtails Ajout Dtails dune Personne retour
MultiActionController
Redirection
Formulaire de saisie des infos dune personne
Redirection
Retour
Saisie Personne
SimpleFormController
Un exemple complet: Gestion des rservations de vol par des personnes Point de dpart: le mtier
Personne
nom prenom
id depart arrivee
*
FabPersonne
getNoms() addPersonne() getPersonne()
*
FabVol
getIds() addVol() getVol()
- Consulter la liste des personnes et avoir la possibilit de saisir une nouvelle personne - Consulter la liste des vols et avoir la possibilit de saisir un nouveau vol - Rserver un vol pour une personne
MultiActionController
Session de lutilisateur
MultiActionController
Liste Personnes
Liste Vols
Saisie Personne R
Formulaire de saisie des infos dune personne Retour
SimpleForm Controller
MultiActionController
SimpleForm Controller
Saisie Vol
Formulaire de saisie des infos dun vol R t Retour
Saisie Personne
Rservation
Saisie Vol
Rservation
Liste slection des noms des personnes Voir Dtails Choisir Confirmer Liste slection des ids des vols Voir Dtails Choisir Annuler
Le fichier gestion-servlet.xml va configurer toute lapplication. 1- On va avoir 5 contrleurs qui seront affects diffrentes URL 1
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/listePersonnes.html">ListePersonnesController</prop> <prop key="/saisiePersonne.html">SaisiePersonneController</prop> <prop key="/listeVols.html">ListeVolsController</prop> <prop key= key="/saisieVol /saisieVol.html html">SaisieVolController</prop> >SaisieVolController</prop> <prop key="/reservation.html">ReservationController</prop> </props> Note: </property> On peut externaliser </bean> dans un fichier
<bean id="ListePersonnesController" class="web.ListePersonnesController"> <property name="methodNameResolver"> <ref local= local="ListeMethodNameResolver"/> ListeMethodNameResolver /> </property> <property name="fabPersonne"> <ref bean="fabriquePersonne"/> </property> </bean>
<bean id="ListeVolsController" class="web.ListeVolsController"> <property name="methodNameResolver"> <ref local= local="ListeMethodNameResolver"/> ListeMethodNameResolver /> </property> <property name="fabVol"> <ref bean="fabriqueVol"/> </property> </bean>
<bean id= id="ReservationController" ReservationController class="web.ReservationController"> <property name="methodNameResolver"> <ref local="ReservationMethodNameResolver"/> </property> <property name="fabVol"> <ref bean="fabriqueVol"/> </property> <property name= name="fabPersonne"> fabPersonne > <ref bean="fabriquePersonne"/> </property> </bean>
<bean id="SaisiePersonneController" class="web.SaisiePersonneController"> l " bS i i P C t ll " <property name="sessionForm"> <value>true</value> </property> <property t name="formView"> "f Vi " <value>saisirPersonne</value> </property> <property name="validator"> <ref f bean="ValidatePersonne"/> b "V lid t P "/ </property> <property name="commandName"> <value>personne</value> </property> / t <property name="fabPersonne"> <ref bean="fabriquePersonne"/> </property> </bean> /b
<bean id="SaisieVolController" class="web.SaisieVolController"> l " b S i i V lC t ll " <property name="sessionForm"> <value>true</value> </property> <property t name="formView"> "f Vi " <value>saisirVol</value> </property> <property name="validator"> <ref f bean="ValidateVol"/> b "V lid t V l"/ </property> <property name="commandName"> <value>vol</value> </property> / t <property name="fabVol"> <ref bean="fabriqueVol"/> </property> </bean> /b
5- Les 2 autres contrleurs sont des Si l F SimpleFormController. C t ll Il Ils ont td des validateurs associs. On leur injecte aussi le mtier.
6- On dfinit la couche mtier dabord d abord les fabriques ici initialises avec deux Personnes et deux Vols
<bean id= id="fabriquePersonne" fabriquePersonne class="metier.FabPersonne"> <property name="personnes"> <map> <entry> <key> <value>Geib</value></key> <ref local="PersonneGeib" /> </entry> <entry> <key> <value>Tison</value></key> <ref local="PersonneTison" /> </entry> </map> </property> </bean> <bean id= id="fabriqueVol" fabriqueVol class="metier.FabVol"> <property name="vols"> <map> <entry> <key> <value>AF322</value></key> <ref local="volAF322" /> </entry> <entry> <key> <value>AF645</value></key> <ref local="volAF645" /> </entry> </map> </property> </bean>
7- Pour finir on dfinit les objets qui sont placs dans les fabriques
<bean id="PersonneGeib" class="metier.Personne"> <property name="nom" value="Geib" /> p p y name="prenom" p <property value="Jean-Marc" /> </bean> <bean id="PersonneTison" class="metier.Personne"> <property p p y name="nom" value="Tison" /> <property name="prenom" value="Sophie" /> </bean> <bean id="volAF322" class="metier.Vol"> <property name="id" value="AF322" /> <property name="depart" value="Lille" /> <property name="arrivee" value="Lyon" /> </bean> <bean id="volAF645" class="metier.Vol"> <property name="id" value="AF645" /> <property p p y name="depart" p value="Paris" /> <property name="arrivee" value="Toulouse" /> </bean>
Note: On peut utiliser un context global pour dclarer ces objets. Voir slides 20 et 21.
5 vues JSP <?xml version="1.0" encoding="ISO_8859-1"?> <!DOCTYPE beans SYSTEM "http://www.springframework.org/dtd/spring-beans.dtd"> et <beans> Le fichier 4 redirections <! <!---> > vues.xml <bean id="listerPersonnes" class="org.springframework.web.servlet.view.JstlView"> <property name="url"><value>/WEB-INF/vues/listerPersonnes.jsp</value></property> Note: </bean> Cest du Spring 2.x <!-- --> <bean id="saisirPersonne" class="org.springframework.web.servlet.view.JstlView"> <property name="url"><value>/WEB-INF/vues/saisirPersonne.jsp</value></property> </bean> <!-- redirectionListePersonnes --> <bean id id="redirectionListePersonnes" redirectionListePersonnes class class="org.springframework.web.servlet.view.RedirectV org.springframework.web.servlet.view.RedirectV <property name="url"><value>/listePersonnes.html</value></property> <property name="contextRelative"><value>true</value></property> <property name="http10Compatible"><value>false</value></property> </bean> <! <!-redirectionSaisiePersonneController --> > <bean id="redirectionSaisiePersonneController" class="org.springframework.web.servlet.view <property name="url"><value>/saisiePersonne.html</value></property> <property name="contextRelative"><value>true</value></property> <property name="http10Compatible"><value>false</value></property> </bean> <!-- listVols --> <bean id="listerVols" class="org.springframework.web.servlet.view.JstlView"> <property name="url"><value>/WEB-INF/vues/listerVols.jsp</value></property> </bean> / <!-- --> <bean id="saisirVol" class="org.springframework.web.servlet.view.JstlView"> <property name="url"><value>/WEB-INF/vues/saisirVol.jsp</value></property> </bean> <! <!-redirectionListeVols --> > <bean id="redirectionListeVols" class="org.springframework.web.servlet.view.RedirectView"> <property name="url"><value>/listeVols.html</value></property> <property name="contextRelative"><value>true</value></property> <property name="http10Compatible"><value>false</value></property>
Reste crire les 5 contrleurs et les 5 vues JSP et les 2 validateurs Voir les sources en annexe
Remarque : Lobjet HttpSession de lutilisateur contient les informations qui doivent tre mmorises entre les appels aux contrleurs
PluginEclipsepourSpring
Bibliography
Spring 3.xtutorials http://www.roseindia.net/spring/spring3/index.shtml htt // i di t/ i / i /i d ht l http://yannart.developpez.com/java/spring/tutoriel/ http://www.theserverside.com/tutorial/Spring h // h id / i l/S i 30 TutorialSettingUpConfiguringTheEnvironment Download http://www.springsource.com/download/community h // i /d l d/ i
Required q Jarfiles
Foratypical webapplicationyou need thefollowing
modulejars:
org.springframework.web.servlet org.springframework.web org springframework asm org.springframework.asm org.springframework.beans org.springframework.core org.springframework.context org.springframework.expression
Notessurlesannotations
Unbean nepeutpasetre declare alafoispar@annotated
etpar<bean></bean>.Sionutiliseles2,ilestdeclare 2 f etle fois, l conteneurrenvoieuneerreuralready l d mapped d SionutiliseSimpleUrlHandlerMapping (danslefichierde config),ilcaptetouslesmapping,etlesmapping faitdans lescontrolleurs sontignors. @Inject vientdeJSR330;permetdefairedelinjection; fonctionneavecSpring 3;Inject lebean detype correspondant;Nepermetpasdespecifier lenomdubean ; @Autowire A i identique id i a@Inject, I j mais i vient i d deSpring. S i Validation LavalidationpeuttreeffectueavecJSR303 Validator; Validator ;Utiliseletag@Valid
Installation
Springcomprend unensembledejarsdebase,necessaire a
Documentations
Tutoriaux http://blog.springsource.com/2011/01/04/green htt //bl i / / / / beans b gettingstartedwithspringmvc/
http://static.springframework.org/docs/Spring p p g g p gMVC
stepbystep/overview.html
2.5.Aadapterpour3.x