0% ont trouvé ce document utile (0 vote)
429 vues82 pages

Cours Spring MVC

Transféré par

Juana del musaique
Copyright
© Attribution Non-Commercial (BY-NC)
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
429 vues82 pages

Cours Spring MVC

Transféré par

Juana del musaique
Copyright
© Attribution Non-Commercial (BY-NC)
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

JeanMarc J M Geib G ib Cedric Dumoulin

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

Retour sur le modle MVC Une application 3tier classique:

U application Une li ti 3ti 3tier avec MVC MVC:

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

Cettemthodereoitlarequte,doitlatraiter(c (cest estdirefabriquerles donnesderponsegrcelacouchemtier)etretournerunobjet ModelAndView LURLassocieestspcifidansleparamtre


@Controller public class HelloWorldController { @RequestMapping("/helloWorld") q pp g( ) public ModelAndView helloWorld() { ModelAndView mav = new ModelAndView(); mav.setViewName("helloWorld"); mav.addObject("date", j , new Date()); ()) return mav; } }

URL

DispatcherServlet HandlerMapping
Choix dun contrleur en fonction de lURL

Metier

MonControleur
HttpServletRequest handleRequest ModelAndView =

N Nom d de vue + Model M d l

Choix d dune une vue

ViewResolver

Page HTML

Vue

Model
fournit par Spring A fournir

Exemple: 1 - Une couche mtier Class Group


public class Groupe { private ArrayList<Object> membres; public ArrayList<Object> getMembres() { return membres; } public void setMembres(ArrayList<Object> membres) { this.membres = membres; } public void addMembre (String membre) { if (membres.contains(membre)) throw h new MembrePresentException(); b i () membres.add(membre); } }

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

Exemple: 3 une page JSP-JSTL pour afficher les membres

<%@ 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

Exemple: 4: dfinir lapplication WEB:


<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java xmlns= http://java.sun.com/xml/ns/javaee sun com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp id= WebApp_ID ID" version= version="2 2.5 5"> > <display-name>testspring3</display-name> On dclare la seule <!-- la servlet --> Servlet principale <servlet> <servlet-name>membres</servlet-name> <servlet name>membres</servlet name> <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <!-- le mapping des url --> <! > <servlet-mapping> <servlet-name>membres</servlet-name> <url-pattern>*.html</url-pattern> </servlet mapping> </servlet-mapping> </web-app>

Ce fichier web.xml ne change jamais. C fi Ce fichier hi est td dans l le rpertoire t i WEB WEB-INF INF

Exemple: 5 le contexte initial souhait de lapplication

Injection de dpendance

groupe: g p

Pierre Paul au Jacques

Une instance de Affichage

Une instance Initialise du mtier

Cela doit tre dcrit dans un fichier WEB-INF/membres-servlet.xml


Nom de la DispatcherServlet

Spring 3.x Exemple p : 5 - le fichier WEB-INF/membres-servlet.xml

<?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

Spring 3.x Exemple p : 5 - le fichier WEB-INF/membres-servlet.xml ( (suite) )

<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

Il faut f t utiliser tili un ViewResolver Vi R l

Il faut les dclarer dans le fichier membres-servlet.xml

Exemple: 6 les mappings dans membres-servlet.xml


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns:p= p "http://www.springframework.org/schema/p" p // p gf g/ /p xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans3.0.xsd http://www.springframework.org/schema/context p // p gf g/ / http://www.springframework.org/schema/context/springcontext3.0.xsd"> <!-- le ViewResolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" g p gf / /> <propertyname="prefix"value="/WEBINF/vues/"/> <propertyname="suffix"value=".jsp"/> Le nom de </bean>

la vue est utilis pour former le nom de la 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

On peut sortir le mapping des vues du fichier de configuration

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

Exemple de ce fichier /WEB-INF/applicationContext.xml pour notre application


<?xml version="1.0" encoding="ISO_8859-1"?> <!DOCTYPE beans SYSTEM "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <! le contexte mtier est la liste de personnes --> <bean id="groupe" class="metier.Groupe"> <property name="membres"> <list> <value>Paul</value> / <value>Mlanie</value> <value>Jacques</value> </list> </property> / </bean> </beans>

Et il faut demander le chargement de ce contexte dans le web.xml


<?xml version= version="1 1.0 0" encoding= encoding="ISO-8859-1"?> ISO 8859 1 ?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app>

<!-- 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

POJO annot @Controller

GET Request

@RequestMapping(method = RequestMethod.GET) processGet(ModelMap model)

Cre ou retrouve

model implicite Objet Command

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

rcuprelemodleimplicite crelobjetcommand lavueaffichantleformulaire

@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 } }

rcupre l lobjet bj tcommand d partirdumodleimplicite

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

Ilnefautplusdclarerlescontrleurs.Ilsserontdcouvertgrceauxannotations Demanderlescanautodesannotations dansmembresservlet.xml


<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: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/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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd htt // http://www.springframework.org/schema/context i f k / h / t t http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Scan package to discover spring annotations --> <context:component-scan base-package="web"/> </beans>

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

Lappli Web avec Spring:

On peut terminer par mettre un welcome file dans le web.xml


<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>

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>

- Dans D confirmation.jsp, fi ti j pour retourner t l la li liste t


<a href="<c:url value="/afficher.html"/>">Retour</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

Lappli est termine et se lance par:


http://localhost:8080/membres

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

groupe.addMembre(commandAjout.getNouveauMembre()); status.setComplete(); return "confirmation"; confirmation ; }

effacelasessionsiok

@ModelAttribute permetdercuprerlobjetcommand. Ilestpeuplpartirdelarequete, requete doncaveclesvaleurssaisiesdansleformulaire. formulaire IlyaconversionimpliciteString>typedanslobjetcommande Ilpeutyavoirplusieur s@ModelAttribute

BindingResult result contient lesventuelles erreurs deconversion


doit tre plac immdiatement aprsle@ModelAttribute auquel il serfere

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 }

Un validator pour dtecter les saisies vide du nouveau membre


package web; import org.springframework.validation.Errors; public class ValidatePersonne implements org.springframework.validation.Validator { /** pour dire que cest un validator de la classe CommandAjout */ public boolean supports(Class classe) { boolean assignableFrom = classe.isAssignableFrom(CommandAjout.class); return assignableFrom; g ; } public void validate(Object obj, Errors erreurs) { // on rcupre la personne poste CommandAjout command = (CommandAjout) obj; // on vrifie le prnom String membre = command.getNouveauMembre(); if (membre == null || membre.trim().length() == 0) { // les erreurs sont stockes dans un objet de type Errors erreurs.rejectValue("nouveauMembre", "commandAjout.nouveauMembre.necessaire", (memberName, msgKey, defaultMsg) "Le nom est ncessaire !"); } } }

void reject(String errorCode)

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.

void reject(String errorCode, Object[] errorArgs, String defaultMessage)


void reject(String errorCode, String defaultMessage) Register a global error for the entire target object, using the given error description. void rejectValue(String field, String errorCode) Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description. void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage) Register a field error for the specified field of the current object (respecting the current nested path path, if any) any), using the given error description description. void rejectValue(String field, String errorCode, String defaultMessage) Register g a field error for the specified p field of the current object j ( (respecting p g the current nested path, if any), 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

<form:errors path =xxxx />


c

Le L tagform:errors f permetdafficher d ffi h l leserreurs

associeslobjetdsignparlepath (reject)ouses attributs(rejectValue). (rejectValue)


<form:form commandName="commandAjout" /> <form:errors path="nouveauMembre" /> </form:form>

Formulairecomplt pourafficher ffi h les l ventuelles ll erreurs(vers>2.5) ( 2 5)


<%@ page language="java" pageEncoding="ISO-8859-1" contentType text/html;charset ISO 8859 1 %> contentType="text/html;charset=ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <head> <title>formulaire Ajout</title> </head> <body> <h3>Formulaire Ajouter un membre</h3> <form:form commandName="commandAjout" acceptCharset="UTF-8"> <form:errors path="*" /> <table> <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> </body> </html>

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">

<form:errors path="*" cssClass="error"/>


<table> <tr> <td><form:label path="nouveauMembre">Nouveau Membre:</form:label></td> <td><form:input path="nouveauMembre" /></td> <%-- Show errors for name field --%>

<td><form:errors path="nouveauMembre" cssClass="error"/></td>


</tr> <tr> <td colspan="3"><input type="submit" value="Envoyer" /></td> </tr> </table> </form:form>

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>

Le fichier messages.properties messages properties :


commandAjout.nouveauMembre.necessaire=Un nom est ncessaire commandAjout.echec=Echec de l'ajout

Il doit tre dans le classpath et il est lu au chargement de lapplication.

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

membres mappings.properties index.jsp WEB-INF web.xml membres-servlet.xml applicationContext.xml

vues

Lappli Web avec Spring:


src

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

<jee:local-slsb> Acces aunbean local <jee:remote-slsb> Acces unbean distant


<jee:local-slsb id= id="myComponent" myComponent jndi-name= jndi-name="ejb/myBean" ejb/myBean business-interface="com.mycom.MyComponent"/> <bean id="myController" class="com.mycom.myController"> <property name name="myComponent" myComponent ref ref="myComponent"/> myComponent /> </bean>

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

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

Simple Form Controller

Formulaire.jsp: <form method = post > . <input type= Submit > </form>

Vue suivante

Get

Lattribut action du formulaire nest pas prcis !

Formulaire
Submit

Simple Form Controller

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

Saisie Nom Controller

public class SaisieNom extends SimpleFormController { protected ModelAndView onSubmit() { return new ModelAndView("redirectionSaisiePrenom" ); } }

Redirection

<bean id="redirectionSaisiePrenom" redirectionSaisiePrenom.class=org.springframework.web.servlet.view.RedirectView class= "org.springframework.web.servlet.view.RedirectView"> redirectionSaisiePrenom.url=/SaisiePrenom.html <property name="url"><value>/SaisiePrenom.html</value></property> </bean> /b

vues.xml

Prnom Submit

Saisie S i i Prenom Controller

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

Affi h Afficher Saisir

Action1 Action2

Methode Action 1

Methode Action 2

retour

Action3

Methode Action 3

suite

MultiActionControleur (Spring3) ( p g )
Classeannot

@Controlleret@RequestMapping( @RequestMapping("/url") /url )


@Controller @RequestMapping("/appointments") q pp g / pp public class AppointmentsController {

Onspcifielurldemapping surlaclasse Lesmthodesannot@RequestMapping g sontrelatives

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" >

Spring 2 Exemple de page jsp dclenchant les actions sur le controleur

<%@ 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>

Les MultiActionController et les SimpleFormController sont la base des applications SpringMVC


Get

Liste slection des noms des personnes Voir Dtails Ajout Dtails dune Personne retour

Methode affichageListe Methode afficherDtails Methode ajoutPersonne

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

Et les cas dutilisation


Vol

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

On dcide du modle MVC de lapplication:


Liste des personnes
Liste slection des noms des personnes Voir Dtails Aj t Ajout

MultiActionController

Session de lutilisateur

MultiActionController

Liste des vols


Liste slection des ids des vols Voir Dtails Aj t Ajout

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

2- Les vues seront dcrites dans le fichier vues.xml


<!-- le resolveur de vues externalisees --> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/vues/vues.xml</value> </property> </bean>

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

3- Trois contrleurs sont des MultiActionController. On leur injecte le mtier ncessaire.

4- On dfinit les actions reconnues par les MultiActionController


<bean id="ListeMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="defaultMethodName"><value>list</value></property> <property name="methodParamNames"> <list> <value>ajout</value> l j / l <value>voir</value> </list> </property> </bean> /b <bean id="ReservationMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="defaultMethodName"><value>list</value></property> <property t name="methodParamNames"> " th dP N " <list> <value>choixVol</value> <value>choixPersonne</value> <value>voirVol</value> l iV l / l <value>voirPersonne</value> <value>confirmer</value> <value>annuler</value> </list> /li t </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

<bean id="ValidatePersonne" class="web.ValidatePersonne"/> <bean id="ValidateVol" class="web.ValidateVol"/>

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.

Cela termine le fichier gestion-servlet.xml ..

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

Pour finir un fichier index.jsp pour entrer dans lapplication


<html> <body><h3> Personnes et vols... <br> Choisissez: <br> <a href= href="<c:url <c:url value= value="listePersonnes listePersonnes.html html"/>">Gestion /> >Gestion des Personnes</a><br> <a href="<c:url value="listeVols.html"/>">Gestion des Vols</a><br> <a href="<c:url value="reservation.html"/>">Gestion des Reservations</a><br> </h3></body> </html>

PluginEclipsepourSpring

http://springide org/project/wiki/SpringideInstall http://springide.org/project/wiki/SpringideInstall

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

Since most webapplicationsuselogging andbasicAOP

features,you need thefollowing required thirdparty offerings:


commonslogging l i 1.1.1

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

lexecution. Ilest aussi possibledetlcharger unenvironement de dvelopement bas sur Eclipse

Lesjaruniquement: http://www.springsource.org/download L Lenvironement environement Eclipse: SpringSource UpdateSiteforEclipse3.7(Release) http://dist.springsource.com/release/TOOLS/update/e3.7

Tlcharger Lenvironement Eclipse p

Documentations
Tutoriaux http://blog.springsource.com/2011/01/04/green htt //bl i / / / / beans b gettingstartedwithspringmvc/

Pasd explication explicationsurcommentrcuperer lesjars, jars lesdployer, dployer

http://static.springframework.org/docs/Spring p p g g p gMVC

stepbystep/overview.html

2.5.Aadapterpour3.x

Vous aimerez peut-être aussi