IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Servlets/JSP Java Discussion :

Cherche un example d'application spring mvc avec éclipse


Sujet :

Servlets/JSP Java

  1. #1
    Membre à l'essai
    Homme Profil pro
    En recherche d’emploi
    Inscrit en
    Mai 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : En recherche d’emploi
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2015
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Cherche un example d'application spring mvc avec éclipse
    Bonjour,

    Comme dans le titre, mon expérience avec mvc date s'il y a 6 ans. Ce serait d'abord pour suivre un cours du soir et un mini projet. Je veux rester en jdbc pour la partie base ainsi que l'on m'a conseillé sur ce forum.

    Quelques une de mes notes:

    Supposons que la servlet soit nommée dispatch, le fichier de configuration va définir servlet-class parameter comme le package qui contient les controller.
    L'annotation @Controller annote la classe qui contient les objets vers lesquels on redirige.
    L'annotation @RequestMapping est une annotation qui est associée au requestDispatcher ou bien au composant HandlerServlet.

    Voyons aussi le contexte original de l'application: si le dispatcher redirige depuis toutes les requêtes définies à partir de / , il prend la charge de tous les contextes débutant par /. exemple: /jspparams.jsp correspond à @requestMapping(jspparam/).

    Voyons par exemple le début d'une méthode mvc prenant en charge la réception des données d'un formulaire par la méthode post
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
     
    MaVue_Controller.java
    @Controller
    class MaVue_Controller {
     
       @RequestMapping("/jspform", requestMethod=RequestMethod.POST)
       public String save_paramsintodb(Model md, Session session, httpServletRequest request) {
        String username=request.getParameter("name");
        String userpassword =request.getParameter("password");
    //... 
        String city=request.getParameter("city");
     
        IDatabaseConfiguration config = new DatabaseMySQLConfiguration();
     
        SignupModel signupmod = new SignupModel(config);
     
        try {
             // do persistence of Parameter using a jdbc based method from class SignupModel
             // then:
              session.addAttribute("user", username); // can be useful for next jsp
     
             return "redirect: /monprofil ";
         } catch (SQLException e) {
            System.out.println("Error with save_paramsintodb method");
            return "redirect: /jspform";
         }
       }
     
    }
    la syntaxe correspond à Spring MVC 3, pour des application plus récentes coté serveur on utilise plutôt la syntaxe
    @GetMapping("/jspform")
    @ResponseBody
    public String getJspparams(@RequestParam String id) {
    return "ID: " + id;
    }

    La configuration suit aussi le pattern ServletDispatcher. Pour indiquer l'endroit où se trouvent les jsp, on a le code suivant dans web.xml

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name ="prefix" value= ("WEB-INF/jsp/") />
    <property name ="prefix" value= (".jsp") />
    </bean>

    Ma motivation est d'utiliser un framework unique pour les vues et tomcat comme container, d'où les choix même ancien. 4 tables en bdd (pas plus, artist, event, instrument, file).
    Merci d'avance

  2. #2
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Vaste question...

    J'ai un projet perso qui utilise Spring:
    https://bitbucket.org/philippegibaul...r40k/src/main/

    Seulement, les choses ont un peu changé depuis.

    Déjà, je n'utilise plus de fichier XML (depuis 2014 pour être exact) mais je gère la configuration avec Spring Boot.

    De plus, je ne déploie pas sur un Tomcat, mais j'ai une classe Main qui lance l'application. De fait, je peux lancer le tout grâce à Docker.

    Enfin, il n'y a pas de client géré par Java (et de fait de JSP). Mon client est une application basé sur angular, lancée par Docker (basé une une image nginx).

    Cordialmement.

  3. #3
    Membre à l'essai
    Homme Profil pro
    En recherche d’emploi
    Inscrit en
    Mai 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : En recherche d’emploi
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2015
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Re: Cherche un example d'application spring mvc avec éclipse
    Merci de votre réponse,

    Je n'ai jamais essayé Docker, bien que je me sois renseigné pour l'installer sous Windows.
    Pour le projet présenté plus haut, j'ai suivi exactement les méthodes d'un cours pour une demo login/password sans succès. Je crains que je ne doive utiliser Hibernate aussi, mais c'est un autre sujet.
    Je reçois bien le conseil faire plutôt dans un conteneur, je pense que je vais faire un dernier test avec Tomcat mais sous Eclipse avant.
    Je ne poste pas le code entier car j'ai consulté plusieurs questions à problème dans ce forum, notamment des configuration avec Spring de Hibernate (chargement des propriétés dialect, show_sql etc dans un bean) et je ne vois pas de différence avec le mien (je le donne ici: https://github.com/tournesol59/eclip...ustomerPersist
    Pour docker, j'ai vu qu'il faut un fichier de configuration où on va indiquer les images, auriez vous une documentation sur l'utilisation de java ee et docker)?
    Merci pour l'idee

  4. #4
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    J'ai regardé très rapidement le projet et j'ai eu une crise cardiaque.

    Pour commencer, il est important de rappeler que Spring est un moteur d'injection de dépendance.
    Spring va instancier les beans Java (terme utiliser par Spring) et les injecter les dépendances pour pouvoir faire tourner l'application.

    On parle d'inversion de contrôle.
    https://fr.wikipedia.org/wiki/Invers..._contr%C3%B4le

    Ensuite, on découpe par couche.

    La couche en bas est la couche DAO, qui communique avec la BDD, Relationnelle, No-SQL, XML...

    Dans mon projet, j'ai définit un contrat de DAO:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
     
    package com.calculateur.warhammer.base.dao;
     
    import java.util.List;
    import java.util.Optional;
     
    import com.calculateur.warhammer.base.entity.IEntity;
    import com.calculateur.warhammer.base.exception.DAOException;
    import com.calculateur.warhammer.base.exception.FunctionnalExeption;
     
    /**
     * DAO pour une entité en BDD
     * @author phili
     *
     * @param <I> Type de l'id de l'entité
     * @param <E> L'entité
     */
    public interface IDAO <I,E extends IEntity<I>>{
     
    	/**
    	 * Sauvegarde l'entité en BDD (Création)
    	 * @param entity L'entité é sauvegarder
    	 * @return L'entité é créer
    	 * @throws DAOException Si probléeme en BDD
    	 * @throws FunctionnalExeption Si probléme à la vérification avant d'insérer en BDD
    	 */
    	E save(E entity)throws DAOException,FunctionnalExeption;
     
    	/**
    	 * Met é jour l'entit en BDD
    	 * @param entity L'entité é modifier
    	 * @return L'entité modifiée
    	 * @throws DAOException Si probléme en BDD
    	 * @throws FunctionnalExeption Si probléme avant de vérifier l'entité
    	 */
    	E update(E entity)throws DAOException,FunctionnalExeption;
     
    	/**
    	 * 
    	 * @param id Id de l'entité
    	 * @return L'id correspondant à l'entité (null sinon)
    	 * @throws DAOException Si probléme en BDD
    	 */
    	Optional<E> getById(I id) throws DAOException;
     
    	/**
    	 * 
    	 * @return La liste des entité présente en BDD
    	 * @throws DAOException Si probléme en BDD
    	 */
    	List<E> getAll() throws DAOException;
     
    	/**
    	 * Efface en BDD l'entité correspondant à l'identifiant
    	 * @param id L'id de l'entité
    	 * @throws DAOException Si probléme en BDD
    	 */
    	void delete(I id)throws DAOException;
     
    	/**
    	 * 
    	 * @return Le nombre d'occurence en BDD
    	 * @throws DAOException
    	 */
    	Long count()throws DAOException;
     
    	/**
    	 * Vérifie la cohérence de l'entité
    	 * @param entity L'entité é vérifier
    	 * @throws DAOException Si erreur lors de recherche en BDD
    	 * @throws FunctionnalExeption Si erreur intrinséque à l'entité
    	 */
    	void verifieEntity(E entity)throws DAOException,FunctionnalExeption;
    }
    Ce n'est pas nécessaire, mais j'ai aussi fait un contrat d'entité:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    package com.calculateur.warhammer.base.entity;
     
    /**
     * Représente une entité en BDD
     * @author phili
     *
     */
    public interface IEntity <I>{
     
    	/**
    	 * 
    	 * @return L'identifiant en BDD
    	 */
    	I getId();
     
    	/**
    	 * Set l'id en BDD
    	 * @param id L'id à setter
    	 */
    	void setId(I id);
    }
    Pour la BDD relationnelle, j'ai fait un Template Method ( https://en.wikipedia.org/wiki/Template_method_pattern ) basé sur JPA/Hibernate:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
     
    package com.calculateur.warhammer.dao.dao;
     
    import java.util.List;
    import java.util.Optional;
     
    import jakarta.persistence.EntityManager;
    import jakarta.persistence.PersistenceContext;
    import jakarta.persistence.Query;
     
     
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.TransactionStatus;
    import org.springframework.transaction.support.DefaultTransactionDefinition;
     
    import com.calculateur.warhammer.base.dao.IDAO;
    import com.calculateur.warhammer.base.entity.IEntity;
    import com.calculateur.warhammer.base.exception.DAOException;
    import com.calculateur.warhammer.base.exception.FunctionnalExeption;
    import com.calculateur.warhammer.dao.verification.VerificationUtils;
     
     
    /**
     * Template Method pour les DAO avec JPA
     * @author phili
     *
     * @param <I> Type de l'id
     * @param <E> Type de l'entité
     */
    public abstract class AbstractDAO<I,E extends IEntity<I>> implements IDAO<I, E>{
     
    	@PersistenceContext
    	protected final EntityManager em;
     
    	protected final PlatformTransactionManager transactionManager;
     
    	protected AbstractDAO(EntityManager em, PlatformTransactionManager transactionManager) {
    		this.em = em;
    		this.transactionManager = transactionManager;
    	}
     
    	/**
    	 * 
    	 * @return La classe sous forme de String pour les Query JPQL
    	 */
    	protected abstract String getEntityClass();
     
    	/**
    	 * 
    	 * @return Le libellé de l'entité pour les query JPQL
    	 */
    	protected abstract String getEntityLibelle();
     
    	/**
    	 * 
    	 * @return Le resource Bundle d'erreur pour les erreurs fonctionnelles
    	 */
    	protected abstract String getErrorBundle();
     
    	/**
    	 * 
    	 * @return L'entité sous forme de classe
    	 */
    	protected abstract Class<E> getClassEntity();
     
    	@Override
    	public E save(E entity) throws DAOException, FunctionnalExeption {
    		verifieEntity(entity);
    		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
    		try {
    			em.persist(entity);
    			transactionManager.commit(status);
    			return entity;
    		}catch (Exception e) {
    			transactionManager.rollback(status);
    			throw new DAOException(e);
    		}
    	}
     
    	@Override
    	public E update(E entity) throws DAOException, FunctionnalExeption {
    		verifieEntity(entity);
    		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
    		try {
    			E rEntity = em.merge(entity);
    			transactionManager.commit(status);
    			return rEntity;
    		}catch (Exception e) {
    			transactionManager.rollback(status);
    			throw new DAOException(e);
    		}
    	}
     
    	@Override
    	public Optional<E> getById(I id) throws DAOException {
    		try {
    			return Optional.ofNullable(em.find(getClassEntity(), id));
    		}catch(Exception e) {
    			throw new DAOException(e);
    		}
    	}
     
    	@SuppressWarnings("unchecked")
    	@Override
    	public List<E> getAll() throws DAOException {
    		try {
    			Query query = em.createQuery(getJpqlAll());
    			return query.getResultList();
    		}catch(Exception e) {
    			throw new DAOException(e);
    		}
    	}
     
    	/**
    	 * 
    	 * @return Le JPQL pour avoir toutes les entités
    	 */
    	private String getJpqlAll() {
    		StringBuilder sb = new StringBuilder("SELECT ");
    		sb.append(getEntityLibelle());
    		sb.append(" FROM ");
    		sb.append(getEntityClass());
    		sb.append(" ");
    		sb.append(getEntityLibelle());
    		return sb.toString();
    	}
     
    	@Override
    	public void delete(I id) throws DAOException {
    		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
    		try {
    			Query queryDelete = getDeleteQuery(id);
    			queryDelete.executeUpdate();
    			transactionManager.commit(status);
    		}catch(Exception e) {
    			transactionManager.rollback(status);
    			throw new DAOException(e);
    		}
     
    	}
     
    	/**
    	 * On laisse la possibilité de surcharger cette méthode au cas où l'id soit complexe (clé sur 2 colonnes par exemple).
    	 * @param id L'id de l'entité à supprimer en BDD.
    	 * @return La query pour effacer l'entité (le paramétrage est fait.
    	 */
    	protected Query getDeleteQuery(I id) {
    		Query query = em.createQuery(getDeleteJpql());
    		query.setParameter("id", id);
    		return query;
    	}
     
    	/**
    	 * On laisse la possibilité de surcharger cette méthode au cas où l'id soit complexe (clé sur 2 colonnes par exemple).
    	 * @return JPQL pour suprimer une entité
    	 */
    	protected String getDeleteJpql() {
    		StringBuilder sb = new StringBuilder("DELETE ");
    		sb.append(" FROM ");
    		sb.append(getEntityClass());
    		sb.append(" ");
    		sb.append(getEntityLibelle());
    		sb.append(" WHERE ");
    		sb.append(getEntityLibelle());
    		sb.append(".id = : id");
    		return sb.toString();
    	}
     
    	@Override
    	public Long count() throws DAOException {
    		try {
    			Query query = em.createQuery(getJpqlCount());
    			return (Long) query.getSingleResult();
    		}catch (Exception e) {
    			throw new DAOException(e);
    		}
    	}
     
    	/**
    	 * 
    	 * @return Le JPQL pour compter ce qui est en BDD.
    	 */
    	private String getJpqlCount() {
    		StringBuilder sb = new StringBuilder("SELECT DISTINCT(COUNT(");
    		sb.append(getEntityLibelle());
    		sb.append(")) FROM ");
    		sb.append(getEntityClass());
    		sb.append(" ");
    		sb.append(getEntityLibelle());
    		return sb.toString();
    	}
     
    	@Override
    	public void verifieEntity(E entity) throws DAOException, FunctionnalExeption {
    		VerificationUtils.verifie(entity, getErrorBundle());
    	}
    }
    Notez que Spring utilise son propre CRUD, instancié directement par Spring:
    https://docs.spring.io/spring-data/c...epository.html

    On peut utiliser d'autres manière de faire (du pur JDBC par exemple) ou s'adapter à une autre BDD (MongoDB, Elasticsearch...)

    On peut aussi utiliser le Design Pattern Adapter si on fixe son contrat et que l'on se base sur l'implémentation de Spring:
    https://en.wikipedia.org/wiki/Adapter_pattern

    Ensuite vient le service, et la DTO. Effectivement, on n'a pas besoin de toutes les informations dans la BDD si l'on donne l'information vers l'extérieur, voir en ajouter de nouvelles (moi, par exemple, je traduit).

    Notez que je ne modifie
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
     
    package com.calculateur.warhammer.base.service;
     
    import java.util.List;
     
    import com.calculateur.warhammer.base.dto.ILibelleDTO;
    import com.calculateur.warhammer.base.exception.FunctionnalExeption;
    import com.calculateur.warhammer.base.exception.ServiceException;
     
    /**
     * Permet de lister les DTO
     * @author phili
     *
     * @param <D> La DTO Type
     */
    public interface IServiceRechercheExistant <D extends ILibelleDTO>{
     
    	/**
    	 * 
    	 * @return Le nombre de DTO existante
    	 * @throws ServiceException
    	 */
    	Long countNombre()throws ServiceException;
     
    	/**
    	 * 
    	 * @param langue Langue de traduction
    	 * @return La liste des DTO traduites
    	 * @throws ServiceException Si erreur de fonctionnement du service
    	 * @throws FunctionnalExeption Si erreur de traduction
    	 */
    	List<D> liste(String langue)throws ServiceException,FunctionnalExeption;
    }
    La DTO:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
     
    package com.calculateur.warhammer.base.dto;
     
    import java.util.Locale;
    import java.util.ResourceBundle;
     
    import com.calculateur.warhammer.base.traduction.ITraduction;
     
    /**
     * Représente une DTO avec un libellé traductible
     * @author phili
     *
     */
    public interface ILibelleDTO extends IDTO<Integer>,ITraduction{
     
    	/**
    	 * 
    	 * @return Le resource Bunble sous forme de String
    	 */
    	String getResourceBudleAsString();
     
    	@Override
    	default ResourceBundle getResourceBundle(Locale locale) {
    		return ResourceBundle.getBundle(getResourceBudleAsString(), locale);
    	}
     
    	/**
    	 * 
    	 * @return Nom de la DTO
    	 */
    	String getNom();
     
    	/**
    	 * Set le nom de la DTO
    	 * @param nom Le nom de la DTO
    	 */
    	void setNom(String nom);
     
    	/**
    	 * 
    	 * @return La cle de traduction de la DTO
    	 */
    	String getCleTraduction();
     
    	/**
    	 * Set clé de traduction
    	 * @param cleTraduction La clé de traduction
    	 */
    	void setCleTraduction(String cleTraduction);	
     
    	/**
    	 * 
    	 * @return Le libelle traduit. Il faut traduire avant.
    	 */
    	String getLibelle();
    }
    Et encore un Template Method:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
     
    package com.calculateur.warhammer.service.service;
     
    import java.io.Serializable;
    import java.util.List;
    import java.util.Locale;
     
    import com.calculateur.warhammer.base.dao.IDAO;
    import com.calculateur.warhammer.base.dto.ILibelleDTO;
    import com.calculateur.warhammer.base.entity.IEntity;
    import com.calculateur.warhammer.base.exception.DAOException;
    import com.calculateur.warhammer.base.exception.FunctionnalExeption;
    import com.calculateur.warhammer.base.exception.ServiceException;
    import com.calculateur.warhammer.base.mapping.IMappingEntityVersDTO;
    import com.calculateur.warhammer.base.service.IServiceRechercheExistant;
    import com.calculateur.warhammer.base.traduction.ILangues;
     
    /**
     * Template Methode pour le service IServiceRechercheExistant.
     * @author phili
     *
     * @param <E> Entité correspondante à la DTO
     * @param <D> Type de DTO
     */
    public abstract class AbstractServiceRechercheExistantFromDAO <I extends Serializable,E extends IEntity<I>,D extends ILibelleDTO>implements IServiceRechercheExistant<D>{
     
    	protected final ILangues langues;
     
    	protected AbstractServiceRechercheExistantFromDAO(ILangues langues) {
    		this.langues = langues;
    	}
     
    	/**
    	 * 
    	 * @return La DAO utilisée
    	 */
    	protected abstract IDAO<I, E> getDAO();
     
    	/**
    	 * 
    	 * @return La classe de Mapping
    	 */
    	protected abstract IMappingEntityVersDTO<E, D> getMapping();
     
    	@Override
    	public Long countNombre() throws ServiceException {
    		try {
    			return getDAO().count();
    		} catch (DAOException e) {
    			throw new ServiceException(e);
    		}
    	}
     
    	@Override
    	public List<D> liste(String langue) throws ServiceException, FunctionnalExeption {
    		try {
    			final Locale locale = langues.getLocale(langue);
    			List<D> list = getMapping().mapEntitiesVersListDTO(getDAO().getAll());
    			list.stream().forEach(t -> t.traduireLibelles(locale));
    			return list;
    		}catch(DAOException e) {
    			throw new ServiceException(e);
    		}
    	}
    }
    Notez que dans les classes fille, on injecte la DAO:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
     
    ackage com.calculateur.warhammer.service.service;
     
    import org.springframework.stereotype.Service;
     
    import com.calculateur.warhammer.base.dao.IDAO;
    import com.calculateur.warhammer.base.mapping.IMappingEntityVersDTO;
    import com.calculateur.warhammer.base.traduction.ILangues;
    import com.calculateur.warhammer.dto.CampDTO;
    import com.calculateur.warhammer.entity.entity.CampEntity;
     
    @Service
    public class CampService extends AbstractServiceRechercheExistantFromDAO<Integer,CampEntity, CampDTO>{
     
    	private IDAO<Integer, CampEntity> campDAO;
     
    	private IMappingEntityVersDTO<CampEntity, CampDTO> campMapping;
     
    	public CampService(ILangues langues, IDAO<Integer, CampEntity> campDAO,
    			IMappingEntityVersDTO<CampEntity, CampDTO> campMapping) {
    		super(langues);
    		this.campDAO = campDAO;
    		this.campMapping = campMapping;
    	}
     
    	@Override
    	protected IDAO<Integer, CampEntity> getDAO() {
    		return campDAO;
    	}
     
    	@Override
    	protected IMappingEntityVersDTO<CampEntity, CampDTO> getMapping() {
    		return campMapping;
    	}
     
    }
    Il n'y aplus qu'à utiliser dans un service REST qui va fournir le JSON:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
     
    package com.calculateur.warhammer.rest.controller;
     
    import java.util.List;
     
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.ResponseBody;
     
    import com.calculateur.warhammer.base.dto.ILibelleDTO;
    import com.calculateur.warhammer.base.exception.FunctionnalExeption;
    import com.calculateur.warhammer.base.exception.ServiceException;
    import com.calculateur.warhammer.base.service.IServiceRechercheExistant;
     
    /**
     * Template Methode pour les service qui récère un ensemble de DTO
     * @author phili
     *
     * @param <D> DTO
     * @param <S> Le type de service utilisé
     */
    public abstract class AbstractListRestController<D extends ILibelleDTO,S extends IServiceRechercheExistant<D>> extends AbstractRestController{
     
    	/**
    	 * 
    	 * @return Le service utilisé par le controlleur
    	 */
    	protected abstract S getService();
     
    	@GetMapping(value = "/all/{langue}",produces = {MediaType.APPLICATION_JSON_VALUE})
    	@ResponseBody
    	public ResponseEntity<List<D>> getAll(@PathVariable("langue")String langue)throws ServiceException,FunctionnalExeption{
    		return ResponseEntity.ok(getService().liste(langue));
    	}
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
     
    package com.calculateur.warhammer.rest.controller;
     
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
     
    import com.calculateur.warhammer.base.service.IServiceRechercheExistant;
    import com.calculateur.warhammer.dto.CampDTO;
     
    @RestController
    @RequestMapping("/camp")
    public class CampController extends AbstractListRestController<CampDTO,IServiceRechercheExistant<CampDTO>>{
     
    	private IServiceRechercheExistant<CampDTO> campService;
     
    	public CampController(IServiceRechercheExistant<CampDTO> campService) {
    		this.campService = campService;
    	}
     
    	@Override
    	protected IServiceRechercheExistant<CampDTO> getService() {
    		return campService;
    	}
    }
    Pour configurer, j'ai effectivement plussieurs configurations selon la BDD (H2 utilisé pour les tests, Postgres en prod).
    Pour la couche DAO:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
     
    package com.calculateur.warhammer.dao.configuration.general;
     
    import javax.sql.DataSource;
     
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.JpaVendorAdapter;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
    import org.springframework.transaction.PlatformTransactionManager;
     
    import com.calculateur.warhammer.base.server.IDatabaseConfiguration;
    import com.calculateur.warhammer.dao.postgresql.ConfigurationPostgresql;
     
    import jakarta.persistence.EntityManager;
     
    /**
     * Configuration abstraite pour Postgresql
     * @author phili
     *
     */
    @ComponentScan(basePackages = {"com.calculateur.warhammer.dao.dao","com.calculateur.warhammer.dao.dao.applicable"})
    public abstract class AbstractConfigurationPostgreSQL {
     
    	@Value("${databaseHost}")
    	private String databaseHost;
     
    	@Value("${loginDatabase}")
    	private String loginDatabase;
     
    	@Value("${passwordDatabase}")
    	private String passwordDatabase;
     
    	@Value("${portDatabase}")
    	private String portDatabase;
     
    	@Value("${databaseName}")
    	private String databaseName;
     
    	@Value("${databaseProperties}")
    	private String databaseProperties;
     
    	@Bean("configurationPostgresql")
    	public IDatabaseConfiguration getConfiguration() {
    		return new ConfigurationPostgresql(databaseHost,loginDatabase,passwordDatabase,portDatabase,databaseName,databaseProperties);
    	}
     
    	/**
    	 * 
    	 * @return Vrai si Hibernate show SQL
    	 */
    	protected abstract boolean isShowSQL();
     
    	/**
    	 * 
    	 * @return Vrai si le sclema doit être créé
    	 */
    	protected abstract boolean isCreateSchema();
     
    	@Bean(name = "localContainerEntityManagerFactoryBean")
    	public LocalContainerEntityManagerFactoryBean getLocalContainerEntityManagerFactoryBean() {
    		LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
    		bean.setDataSource(getDataSource());
    		bean.setPackagesToScan("com.calculateur.warhammer.entity.entity");
    		bean.setJpaVendorAdapter(getJpaVendorAdapter());
    		return bean;
    	}
     
    	@Bean(name = "jpaVendorAdapter")
    	public JpaVendorAdapter getJpaVendorAdapter() {
    		HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    		adapter.setShowSql(isShowSQL());
    		adapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
    		adapter.setGenerateDdl(isCreateSchema());
    		return adapter;
    	}
     
    	@Bean("entityManager")
    	public EntityManager getEntityManager() {
    		return getLocalContainerEntityManagerFactoryBean().getNativeEntityManagerFactory().createEntityManager();
    	}
     
    	@Bean(name = "dataSource")
    	public DataSource getDataSource() {
    		IDatabaseConfiguration conf = getConfiguration();
    		DataSourceBuilder<?> builder = DataSourceBuilder.create();
    		builder.driverClassName(conf.getClassDriver());
    		builder.url(conf.getJDBCUrl());
    		builder.username(conf.getUser());
    		builder.password(conf.getPassword());
     
    		return builder.build();
    	}
     
    	@Bean(name = "transactionManager")
    	public PlatformTransactionManager getTransactionManager() {
    		JpaTransactionManager transactionManager
            = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(
            getLocalContainerEntityManagerFactoryBean().getObject() );
          return transactionManager;
    	}
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    package com.calculateur.warhammer.dao.configuration;
     
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
     
    import com.calculateur.warhammer.dao.configuration.general.AbstractConfigurationPostgreSQL;
     
    /**
     * Configuration concrète de Postgresql, sur une BDD existante et à jour
     * @author phili
     *
     */
    @Configuration
    public class ConfigurationPostgreSQL extends AbstractConfigurationPostgreSQL{
     
    	@Value("${isShowSQL}")
    	private boolean isShowSQL;
     
    	@Override
    	protected boolean isShowSQL() {
    		return isShowSQL;
    	}
     
    	@Override
    	protected boolean isCreateSchema() {
    		return false;
    	}
     
    }
    Pour la couche service:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
     
    package com.calculateur.warhammer.service.configuration.general;
     
    import java.lang.reflect.InvocationTargetException;
    import java.util.HashMap;
    import java.util.Locale;
    import java.util.Map;
     
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
     
    import com.calculateur.warhammer.base.traduction.ILangues;
    import com.calculateur.warhammer.base.traduction.LanguesImplementation;
    import com.calculateur.warhammer.calcul.mort.parametres.IParametres;
    import com.calculateur.warhammer.calcul.mort.parametres.ParametresBuilder;
    import com.calculateur.warhammer.data.regles.factory.factory.FactoryFactoryRegles;
    import com.calculateur.warhammer.data.regles.factory.factory.IFactoryFactoryRegle;
    import com.calculateur.warhammer.service.configuration.introspection.ValidationIntrospectionUtil;
     
    /**
     * Configuration des services par Spring boot
     * @author phili
     *
     */
    @ComponentScan(basePackages = {"com.calculateur.warhammer.service.service","com.calculateur.warhammer.service.mapping"})
    public class AbstractConfigurationService {
     
    	@Bean(name = "langues")
    	public ILangues getLangues() {
    		Locale defaut = Locale.FRANCE;
    		Map<String, Locale> map = new HashMap<>();
    		map.put("fr", Locale.FRANCE);
    		map.put("en", Locale.ENGLISH);
    		return new LanguesImplementation(defaut, map);
    	}
     
    	//Fabrication de règle
    	@Bean(name = "factoryFactoryRegle")
    	public IFactoryFactoryRegle getFactoryFactoryRegle() {
    		return new FactoryFactoryRegles();
    	}
     
    	//Paramètres calcul
    	@Bean(name = "parametres")
    	public IParametres getParametres() throws SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    		final ParametresBuilder builder = ParametresBuilder.getInstance();
    		ValidationIntrospectionUtil.getListValidationPhaseTir().forEach(builder::addValidationPhaseTir);
    		ValidationIntrospectionUtil.getListValisationTirContreCharge().forEach(builder::addValidationTirContreCharge);
    		ValidationIntrospectionUtil.getListValisationCorpsACorps().forEach(builder::addValidationCorpsACorps);
    		return builder.build();
    	}
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    package com.calculateur.warhammer.service.configuration;
     
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
     
    import com.calculateur.warhammer.dao.configuration.ConfigurationPostgreSQL;
    import com.calculateur.warhammer.service.configuration.general.AbstractConfigurationService;
     
    /**
     * Configuration service pour la Prod avec Postgresql
     * @author phili
     *
     */
    @Configuration
    @Import(value = {ConfigurationPostgreSQL.class})
    public class ConfigurationService extends AbstractConfigurationService{
     
    }
    Et la couche REST:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
     
    package com.calculateur.warhammer.rest.configuration.general;
     
    import java.util.Arrays;
     
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     
    /**
     * Configuration pour les service REST pour Spring Boot
     * @author phili
     *
     */
    @ComponentScan(basePackages = {"com.calculateur.warhammer.rest.controller"})
    public class AbstractRestConfiguration implements WebMvcConfigurer{
     
    	@Value("${clientWeb}")
    	private String clientWeb;
     
    	@Bean("securityFilterChain")
    	public SecurityFilterChain getFilterChain(HttpSecurity http) throws Exception {
    			return http
    				.cors().configurationSource(getCorsConfigurationSource())
    					.and()
    				.csrf().disable()	
    				.build();
    	}
     
    	@Bean("corsConfigurationSource")
    	public CorsConfigurationSource getCorsConfigurationSource() {
    		CorsConfiguration configuration = new CorsConfiguration();
    		configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    		configuration.applyPermitDefaultValues();
    		configuration.addAllowedOrigin(clientWeb);
    		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    		source.registerCorsConfiguration("/**", configuration);
    		return source;
    	}	
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
     
    package com.calculateur.warhammer.rest.configuration;
     
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
     
    import com.calculateur.warhammer.rest.configuration.general.AbstractRestConfiguration;
    import com.calculateur.warhammer.service.configuration.ConfigurationService;
     
    /**
     * Configuration REST pour la PROD
     * @author phili
     *
     */
    @Configuration
    @EnableWebMvc
    @Import(value = {ConfigurationService.class})
    public class RestConfiguration extends AbstractRestConfiguration{
     
    }
    Docker peut tranquilement lancer un serveur Tomcat avec les REST Controlleur:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
     
    package com.calculateur.warhammer.rest.server;
     
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
    import org.springframework.context.annotation.Import;
     
    import com.calculateur.warhammer.rest.configuration.RestConfiguration;
     
    /**
     * Serveur Web pour la PROD
     * @author phili
     *
     */
    @Import(value = {RestConfiguration.class})
    @EnableAutoConfiguration
    public class ServerWeb extends SpringBootServletInitializer{
     
    	public static void main(String [] args) {
    		SpringApplication.run(ServerWeb.class, args);
    	}
    }
    A noter qu'ici, il n'y a pas de client (page HTML). Il fut faire un client pour communiquer avec le back. Le mien est en Angular.

  5. #5
    Membre à l'essai
    Homme Profil pro
    En recherche d’emploi
    Inscrit en
    Mai 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : En recherche d’emploi
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2015
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Re: cherche un exemple.. Spring
    Pourriez vous, je vous en prie, répondre à une question.
    On utilise Spring pour faire de l’injection de dépendance. Là dans votre code ce sont les instances filles dérivées de AbstractServiceRechercheExistantFromDAO qui ont besoin de l’entité ILangue. Est-ce exact?
    Si je crée, dans mon projet, une classe InstrumentService qui sert à créer des instances Instrument qui ont besoin d’une dépendance de type Musician, là je comprends la DI au niveau de ce Service.
    Je mettrai plus de code actuel sur mon site après. Bonne journée

  6. #6
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    C'est que mes services font ... toujours la même chose.

    Comme je n'aime pas me répéter, j'ai fait un TemplateMethode qui le fait qu'une seule fois.

    C'est donc la classe fille qui est injecté dans le contexte de Spring, avec par exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     
    package com.calculateur.warhammer.rest.controller;
     
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
     
    import com.calculateur.warhammer.base.service.IServiceRechercheExistant;
    import com.calculateur.warhammer.dto.BatimentDTO;
     
    @RestController
    @RequestMapping("/batiment")
    public class BatimentController extends AbstractListRestController<BatimentDTO, IServiceRechercheExistant<BatimentDTO>>{
     
    	private final IServiceRechercheExistant<BatimentDTO> batimentService;
     
    	public BatimentController(IServiceRechercheExistant<BatimentDTO> batimentService) {
    		this.batimentService = batimentService;
    	}
     
    	@Override
    	protected IServiceRechercheExistant<BatimentDTO> getService() {
    		return batimentService;
    	}
     
    }
    Pour signaler que l'on a un service REST:
    Et que l'on a dans l'URL "/batiment":
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    @RequestMapping("/batiment")
    Il faut donc dire à Spring de faire de l'introspection dans le package (où il y a plein de @RestController).

    Là aussi, j'ai 2 configurations (1 pour Docker qui tape dans Postgresql, 1 pour les tests qui tape dans H2).

    J'utilise encore un Template Method.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
     
    package com.calculateur.warhammer.rest.configuration.general;
     
    import java.util.Arrays;
     
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     
    /**
     * Configuration pour les service REST pour Spring Boot
     * @author phili
     *
     */
    @ComponentScan(basePackages = {"com.calculateur.warhammer.rest.controller"})
    public class AbstractRestConfiguration implements WebMvcConfigurer{
     
    	@Value("${clientWeb}")
    	private String clientWeb;
     
    	@Bean("securityFilterChain")
    	public SecurityFilterChain getFilterChain(HttpSecurity http) throws Exception {
    			return http
    				.cors(cors -> getCorsConfigurationSource())
    				.csrf(csrf -> csrf.disable())	
    				.build();
    	}
     
    	@Bean("corsConfigurationSource")
    	public CorsConfigurationSource getCorsConfigurationSource() {
    		CorsConfiguration configuration = new CorsConfiguration();
    		configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    		configuration.applyPermitDefaultValues();
    		configuration.addAllowedOrigin(clientWeb);
    		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    		source.registerCorsConfiguration("/**", configuration);
    		return source;
    	}	
    }
    Pour introspecter le package:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    @ComponentScan(basePackages = {"com.calculateur.warhammer.rest.controller"})

  7. #7
    Membre à l'essai
    Homme Profil pro
    En recherche d’emploi
    Inscrit en
    Mai 2015
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : En recherche d’emploi
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2015
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Merci
    Merci beaucoup pour votre réponse et je m'excuse pour ma question qui n'était pas claire.
    Par contre je ne connais pas du tout les services Rest. Je consulte souvent le site gayerie.dev sur SpringBoot
    Merci encore

  8. #8
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    A titre d'information (je le fais sur un projet au travail), pour rediriger vers une page HTML/JSP:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
     
    package fr.cisirh.explorateur.controller;
     
    import java.io.IOException;
     
    import javax.servlet.http.HttpServletResponse;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
     
    import fr.cisirh.explorateur.controller.util.ConfigurationApplication;
     
    /**
     * Controlleur appeelée lors de l'appel de l'application par Open HR. On redirige vers les pages index.html construites avec Vue.je.
     * @author pgibault-adc
     *
     */
    @Controller
    public class IndexController {
     
    	private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);
     
    	private static final String PATH_APPLICATION_BASE = "./application/index.html";
     
    	private static final String PATH_APPLICATION_ADMINISTRATION = "./configuration/index.html";
     
    	private static final String PATH_NON_DISPONIBLE = "./applicationNonDisponible.html";
     
    	private final ConfigurationApplication configurationApplication;
     
    	public IndexController(ConfigurationApplication configurationApplication) {
    		this.configurationApplication = configurationApplication;
    	}
     
    	/**
    	 * Redirige vers l'application.
    	 * @param response Réponse HTTP
    	 * @throws IOException
    	 */
    	@RequestMapping(value =  {"" ,"/"})
        public void redirectApplication(HttpServletResponse response) throws IOException {
            String path = configurationApplication.isDisponible()?PATH_APPLICATION_BASE:PATH_NON_DISPONIBLE;
            LOGGER.debug("Redirect..."+path);
            response.sendRedirect(path);
        }
     
    	/**
    	 * Redirige vers l'application administrateur.
    	 * @param response Réponse HTTP.
    	 * @throws IOException
    	 */
    	@RequestMapping(value =  {"/configuration"})
        public void redirectAdministration(HttpServletResponse response) throws IOException {
            String path = configurationApplication.isDisponible()?PATH_APPLICATION_ADMINISTRATION:PATH_NON_DISPONIBLE;
            LOGGER.debug("Redirect..."+path);
            response.sendRedirect(path);
        }
    }
    On spécifie à Spring Boot le controlleur par:
    Et on spécifie le mapping par:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    @RequestMapping(value =  {"" ,"/"})
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    @RequestMapping(value =  {"/configuration"})
    Et on redirige vers la page par:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    response.sendRedirect(path);

Discussions similaires

  1. Réponses: 2
    Dernier message: 22/11/2016, 13h06
  2. [Framework] Application Spring MVC , hibernate, Maven, GWT
    Par azur123 dans le forum Spring
    Réponses: 1
    Dernier message: 30/04/2014, 07h46
  3. Problème d'éxecution de mon application Spring MVC avec Tomcat
    Par Eric_beauvais dans le forum Tomcat et TomEE
    Réponses: 0
    Dernier message: 29/10/2013, 19h01
  4. Réponses: 4
    Dernier message: 17/04/2013, 20h25
  5. Réponses: 1
    Dernier message: 30/03/2013, 21h26

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo