MVC Modèle-Vue-Contrôleur Exemple d application



Documents pareils
Supervision et infrastructure - Accès aux applications JAVA. Document FAQ. Page: 1 / 9 Dernière mise à jour: 15/04/12 16:14

TP JEE Développement Web en Java. Dans ce TP nous commencerons la programmation JEE par le premier niveau d une application JEE : l application web.

OpenPaaS Le réseau social d'entreprise

Projet Java EE Approfondi

Web Tier : déploiement de servlets

La persistance des données dans les applications : DAO, JPA, Hibernate... COMPIL 2010 francois.jannin@inp-toulouse.fr 1

Alfstore workflow framework Spécification technique

Once the installation is complete, you can delete the temporary Zip files..

Architecture Orientée Service, JSON et API REST

Exercices sur SQL server 2000

WEB page builder and server for SCADA applications usable from a WEB navigator

Quelques patterns pour la persistance des objets avec DAO DAO. Principe de base. Utilité des DTOs. Le modèle de conception DTO (Data Transfer Object)

Cedric Dumoulin (C) The Java EE 7 Tutorial

Extension SSO Java. Cette note technique décrit la configuration et la mise en œuvre du filtre de custom SSO Java.

Avant-propos 1. Avant-propos Organisation du guide À qui s'adresse ce guide?...4

Instructions pour mettre à jour un HFFv2 v1.x.yy v2.0.00

Projet de programmation (IK3) : TP n 1 Correction

How to Login to Career Page

1. Installation d'un serveur d'application JBoss:

Compléter le formulaire «Demande de participation» et l envoyer aux bureaux de SGC* à l adresse suivante :

3615 SELFIE. HOW-TO / GUIDE D'UTILISATION

Outil de planification en ligne pour des créations de rendez-vous ou de sondage

Serveur d'application Client HTML/JS. Apache Thrift Bootcamp

Academic Project. B2- Web Development. Resit Project. Version 1.0 Last update: 24/05/2013 Use: Students Author: Samuel CUELLA

Cheque Holding Policy Disclosure (Banks) Regulations. Règlement sur la communication de la politique de retenue de chèques (banques) CONSOLIDATION

Get Instant Access to ebook Cest Maintenant PDF at Our Huge Library CEST MAINTENANT PDF. ==> Download: CEST MAINTENANT PDF

Corrigé des exercices sur les références

lundi 3 août 2009 Choose your language What is Document Connection for Mac? Communautés Numériques L informatique à la portée du Grand Public

27/11/12 Nature. SDK Python et Java pour le développement de services ACCORD Module(s)

calls.paris-neuroscience.fr Tutoriel pour Candidatures en ligne *** Online Applications Tutorial

Les Portfolios et Moodle Petit inventaire

OUTIL DE TRAVAIL COLLABORATIF

RAPID Prenez le contrôle sur vos données

First Nations Assessment Inspection Regulations. Règlement sur l inspection aux fins d évaluation foncière des premières nations CONSOLIDATION

Paris Airports - Web API Airports Path finding

Formation Webase 5. Formation Webase 5. Ses secrets, de l architecture MVC à l application Web. Adrien Grand <jpountz@via.ecp.fr> Centrale Réseaux

Application web de gestion de comptes en banques

Instructions Mozilla Thunderbird Page 1

MANUEL MARKETING ET SURVIE PDF

If the corporation is or intends to become a registered charity as defined in the Income Tax Act, a copy of these documents must be sent to:

Application Form/ Formulaire de demande

Création d un service web avec NetBeans 5.5 et SJAS 9

Contents Windows

Mon Service Public - Case study and Mapping to SAML/Liberty specifications. Gaël Gourmelen - France Telecom 23/04/2007

Grégoire de Lassence. Copyright 2006, SAS Institute Inc. All rights reserved.

ADMINISTRATION DE ADOBE LIVECYCLE MOSAIC 9.5

Forthcoming Database

4. Outils pour la synchronisation F. Boyer, Laboratoire Lig

Apache Camel. Entreprise Integration Patterns. Raphaël Delaporte BreizhJUG

Surveillance de Scripts LUA et de réception d EVENT. avec LoriotPro Extended & Broadcast Edition

JavaServer Pages (JSP)

Paxton. ins Net2 desktop reader USB

TABLE DES MATIERES A OBJET PROCEDURE DE CONNEXION

Natixis Asset Management Response to the European Commission Green Paper on shadow banking

Plan. Department of Informatics

SERVEUR DÉDIÉ DOCUMENTATION

Auto-évaluation Programmation en Java

English version Legal notice

MELTING POTES, LA SECTION INTERNATIONALE DU BELLASSO (Association étudiante de lʼensaparis-belleville) PRESENTE :

Acronymes et abréviations. Acronymes / Abbréviations. Signification

et Active Directory Ajout, modification et suppression de comptes, extraction d adresses pour les listes de diffusion

Institut Supérieur de Gestion. Cours pour 3 ème LFIG. Java Enterprise Edition Introduction Bayoudhi Chaouki

AMENDMENT TO BILL 32 AMENDEMENT AU PROJET DE LOI 32

API04 Contribution. Apache Hadoop: Présentation et application dans le domaine des Data Warehouses. Introduction. Architecture

Exemple PLS avec SAS

CETTE FOIS CEST DIFFERENT PDF

RULE 5 - SERVICE OF DOCUMENTS RÈGLE 5 SIGNIFICATION DE DOCUMENTS. Rule 5 / Règle 5

CEST POUR MIEUX PLACER MES PDF

Quick Start Guide This guide is intended to get you started with Rational ClearCase or Rational ClearCase MultiSite.

Création d une application JEE

Programmation Par Objets

MapReduce. Malo Jaffré, Pablo Rauzy. 16 avril 2010 ENS. Malo Jaffré, Pablo Rauzy (ENS) MapReduce 16 avril / 15

DOCUMENTATION MODULE BLOCKCATEGORIESCUSTOM Module crée par Prestacrea - Version : 2.0

Java Aspect Components (JAC)

Nouveautés printemps 2013

Utiliser une WebCam. Micro-ordinateurs, informations, idées, trucs et astuces

Editing and managing Systems engineering processes at Snecma

Vanilla : Virtual Box

Tutoriel d installation de Hibernate avec Eclipse

A l'avenir, chacun aura son quart d'heure de célébrité.. Andy WAHROL

AGROBASE : un système de gestion de données expérimentales

GIGABIT PCI DESKTOP ADAPTER DGE-530T. Quick Installation Guide+ Guide d installation+

Notice Technique / Technical Manual

Introduction aux «Services Web»

Differential Synchronization

Construction d'une application MVC distribuée avec Spring Remoting. Partie 1 : HttpInvoker, Hessian, Burlap, RMI

1.The pronouns me, te, nous, and vous are object pronouns.

Judge Group: P Title: Quel est meilleur: le compost ou le fertilisant chimique? Student(s): Emma O'Shea Grade: 6

Flex. Lire les données de manière contrôlée. Programmation Flex 4 Aurélien VANNIEUWENHUYZE

DOCUMENTATION - FRANCAIS... 2

LOGICIEL D'ADMINISTRATION POUR E4000 & G4000 MANAGEMENT SOFTWARE FOR E4000 & G4000

UNIVERSITY OF MALTA FACULTY OF ARTS. French as Main Area in an ordinary Bachelor s Degree

Package Contents. System Requirements. Before You Begin

Support Orders and Support Provisions (Banks and Authorized Foreign Banks) Regulations

Lambda! Rémi Forax Univ Paris-Est Marne-la-Vallée

Compte Rendu d intégration d application

Le passé composé. C'est le passé! Tout ça c'est du passé! That's the past! All that's in the past!

PARIS ROISSY CHARLES DE GAULLE

Transcription:

MVC Modèle-Vue-Contrôleur Exemple d application 0.1 Rappels La plateforme Spring MVC repose sur un DispatcherServlet qui gère toutes les requêtes. En rappel, nous avons vu lors du cours JSP et servlet que les requêtes sont reçues sous la forme de requêtes HTTP envoyées par un client web. Les requêtes sont ensuite encapsulées dans l objet HttpRequest et passées à la servlet. Dans le cadre de la plateforme Spring MVC, les requêtes sont plutôt passées au DispatcherServlet. Le DispatcherServlet consulte ensuite un handler mapping 1 et désignera par la suite le contrôleur qui se chargera du traitement de la requête. La requête est traitée par le contrôleur et celui-ci retourne un objet de type ModelAndView : le ModelAndView : contient à la fois le Modèle et la Vue. Il existe 3 types de handler mapping dans la plateforme Spring MVC : 1. BeanNameUrlHandlerMapping 2. ControllerClassNameHandlerMapping 3. SimpleUrlHandlerMapping example 0.2 Début de l exemple d application Créez un projet web dynamique et configurez le fichier web.xml ainsi qu il suit : web.xml <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.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" version="2.5"> <display-name>springmvc</display-name> <!-- The parameter tells about the location of configuration XML. Usually all the data access beans and service layer beans are kept here. You can register more than one XML here. --> <context-param> 1. Composant logiciel qui affecte les requêtes aux contrôleurs 1

<param-name>contextconfiglocation</param-name> <param-value>web-inf/applicationcontext.xml</param-value> </context-param> <!-- The listener is reponsible for building the spring container. It looks for all configuration XML as defined by parameter contextconfiglocation and also looks for a configuration which is named as Dispatch Servlet name. In this case it will be named as springapp-servlet.xml --> <listener> <listener-class> org.springframework.web.context.contextloaderlistener </listener-class> </listener> <!-- Dispatcher Servlet which traps all the request targeted for Spring MVC --> <servlet> <servlet-name>springapp</servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Mapping for the request. It can be anything --> <servlet-mapping> <servlet-name>springapp</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> </web-app> Librairies à inclure dans le projet jakarta-commons/commons-logging.jar mysql-connector-java-5.1.18 j2ee/jstl.jar log4j/log4j-1.2.14.jar jakarta-taglibs/standard.jar dist/spring.jar dist/modules/spring-webmvc.jar 0.3 Couche d accès aux données Student.java /** * Java bean which will be used to save and retrieve data. * */ public class Student { protected String name; //Getters and setters public String getname() { return name; public void setname(string name) { this.name = name; L interface DAO public interface StudentDao { public void savestudent(student student); public List<Student> getallstudents(); 2

L implementation du DAO public class StudentJdbcDao implements StudentDao { protected SimpleJdbcTemplate simplejdbctemplate; public void setsimplejdbctemplate(simplejdbctemplate simplejdbctemplate) { this.simplejdbctemplate = simplejdbctemplate; public void savestudent(student student) { simplejdbctemplate.update("insert into STUDENT (name) values (?)",student.getname()); public List<Student> getallstudents() { return simplejdbctemplate.query ("Select name as Name from Student", new ParameterizedRowMapper<Student>(){ public Student maprow(resultset rs,int rownum) throws SQLException { Student student = new Student(); student.setname(rs.getstring("name")); return student; ); Les classes DAO doivent être enregistrées en tant que bean dans Spring. Cela se fera dans le fichier de configuration applicationcontext.xml. Ce fichier est est reférencé dans le fichier de configuration web.xml à travers la balise contextconfiglocationcréez le premier fichier de configuration suivant : applicationcontext.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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- The Dao class --> <bean id="studentdao" class="com.oyejava.springmvc.studentjdbcdao"> <property name="simplejdbctemplate" ref="jdbctemplate" /> <!-- Template class to access JDBC code --> <bean id="jdbctemplate" class="org.springframework.jdbc.core.simple.simplejdbctemplate"> <constructor-arg ref="datasource" /> <!-- Configuration for the data source --> <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource" destroy-method="close"> <property name="driverclassname" value="org.hsqldb.jdbcdriver" /> <property name="url" value="jdbc:hsqldb:hsql://localhost" /> <property name="username" value="sa" /> <property name="password" value="" /> </beans> 3

Créez le second fichier de configuration suivant ; ce second fichier est lui aussi reférencé dans le fichier web.xml : springapp-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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="studentlistcontroller" class="com.oyejava.springmvc.studentlistcontroller"> <!-- command class and command name are used to retrieve and set the value as name value pair in HttpRequest and Response. The form view tells that when the request comes for this Controller than which form to display in which user input can be taken. --> <bean id="studentcreatecontroller" class="com.oyejava.springmvc.studentcreatecontroller"> <property name="formview" value="createstudent" /> <property name="commandname" value="student" /> <property name="commandclass" value="com.oyejava.springmvc.student" /> <bean id="simpleurlmapping" class="org.springframework.web.servlet.handler.simpleurlhandlermapping"> <property name="mappings"> <props> <prop key="/studentlist.htm">studentlistcontroller</prop> <prop key="/createstudent.htm">studentcreatecontroller</prop> </props> <bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix"> <value>/web-inf/jsp/</value> <property name="suffix"> <value>.jsp</value> </beans> Dans le fichier web.xml : 1. le contexte créé par l objet contextconfiglocationdefinit le contexte global de l application ; 2. le contexte créé par le fichier springapp-servletdéfinit le context enfant et se refère aux beans déclaré dans le contexte général. Par exemple, le bean studentcreatecontroller se refère à studentdao.le bean studentdaoest déclaré dans le contexte général. A l intérieur de la classe du contrôleur : /** * The controller class which is used to take the user input and * process the data at the backend */ public class StudentCreateController extends SimpleFormController { protected StudentDao studentdao; public void setstudentdao(studentdao studentdao) { this.studentdao = studentdao; //The is object which is used to set the values when the form is //displayed first time protected Object formbackingobject(httpservletrequest request) throws Exception { Student student = new Student(); student.setname("default Name"); return student; 4

//This method is called when the form is submitted by the user. //The command class is Student so Spring automatically parses the //HttpRequest object, retrieves the name value pair out of it and //sets the properties in the command object. protected ModelAndView onsubmit(object command) throws Exception { Student student = (Student) command; studentdao.savestudent(student); return new ModelAndView("redirect:/studentList.htm"); Créez la classe contenant le contrôleur chargé de l affichage de la liste des étudiants : StudentDao public class StudentListController extends AbstractController { protected StudentDao studentdao; public void setstudentdao(studentdao studentdao) { this.studentdao = studentdao; // This issues a request to database through data access layer and //gets the list of students. The list of students is put inside a //ModelAndView Object protected ModelAndView handlerequestinternal(httpservletrequest arg0, HttpServletResponse arg1) throws Exception { List<Student> studentlist = studentdao.getallstudents(); //studentlist - This is the logical view id and based on view resolve //will get converted into a physical view which can be a jsp file //students - This is the name of the parameter against which the list // will be stored. //This will be used in jsp file to access the student list object. //studentlist - studentlist object. return new ModelAndView("studentList","students",studentList); Comment le dispatcheur de servlet DispatcherServlet sait-il exactement quel contrôleur doit être invoqué lors qu une requête lui est transmise? C est le handler mapper qui s en charge. Par exemple, dans le fichier springapp-servlet.xml le handler mapper portant le nom simpleurlmapping est utilisé. La propriété du bean concerné indique quel type d URL doit correspondre à un contrôleur donnée. Ci-dessous, un exemple de configuration du controleur StudentListController <bean id="/studentlist.htm" class="com.oyejava.springmvc.studentlistcontroller"> 0.4 Les vues Les vues sont des fichiers de type.jsp createstudent.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <body> <form:form commandname="student"> <label for="name">name:</label> <form:input path="name" /> <input type="submit" value="register" /> </form:form> </body> 5

studentlist.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <body> <c:foreach items="${students" var="student"> <tr> <td>${student.name <br/></td> </tr> </c:foreach> </body> 0.5 L intercepteur LoggingInterceptor.java public class LoggingInterceptor extends HandlerInterceptorAdapter { private static Logger log = Logger.getLogger(LoggingInterceptor.class); public boolean prehandle(httpservletrequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub log.info("entered for processing request"); return true; public void posthandle(httpservletrequest request, HttpServletResponse response, Object handler, ModelAndView modelandview) throws Exception { log.info("exited for processing request"); Enregistrement de l intercepteur dans le fichier springapp-servlet.xml <bean id="logginginterceptor" class="com.oyejava.springmvc.logginginterceptor" /> <bean id="simpleurlmapping" class="org.springframework.web.servlet.handler.simpleurlhandlermapping"> <property name="interceptors"> <list> <ref local="logginginterceptor" /> </list> <property name="mappings"> <props> <prop key="/studentlist.htm"> studentlistcontroller </prop> <prop key="/createstudent.htm"> studentcreatecontroller </prop> </props> 0.6 Internationalisation and localisation Configuration de l objet messagesource dans le fichier springapp-servlet.xml <bean id="messagesource" class="org.springframework.context.support.resourcebundlemessagesource"> <property name="basename"> <value>messages</value> 6

src/messages.properties name=name save=save src/messages_de_de.properties Name=Name save=außer 0.7 validation Il s agit du mécanisme de validation des données saisies dans les vues : StudentValidator.java public class StudentValidator implements Validator { public boolean supports(class clazz) { return clazz.equals(student.class); // Actual validate method public void validate(object obj, Errors errors) { //command object is also available Student student = (Student)obj; //emptyfield is resolved by looking into the properties file //of locale. If it is not present than the fourth argument //is used to display locale message ValidationUtils.rejectIfEmptyOrWhitespace (errors, "name", "emptyfield","field empty"); Enregistrement du validator au niveau du contrôleur : <bean id="studentcreatecontroller" class="com.oyejava.springmvc.studentcreatecontroller"> <property name="formview" value="createstudent" /> <property name="commandname" value="student" /> <property name="commandclass" value="com.oyejava.springmvc.student" /> <property name="validator"> <bean class="com.oyejava.springmvc.studentvalidator" /> createstudent.jsp <body> <spring:hasbinderrors name="student"> <c:foreach var="error" items="${errors.allerrors"> <spring:message code="${error.code" text="${error.defaultmessage" /> </c:foreach> </spring:hasbinderrors> <form:form commandname="student"> <label for="name"><spring:message code="name" /></label> <form:input path="name" /> <input type="submit" value=<spring:message code="save"/> /> </form:form> </body> 7