web-dev-qa-db-fra.com

Comment configurer angular 4 dans un projet de guerre Java basé sur Maven

Je deviens un peu fou parce que je ne trouve pas de guide pour configurer une application angulaire 4 dans un projet de guerre Java qui sera construit avec Maven. C'est parce que je veux l'exécuter sur un serveur Wildfly.

De l'aide?

Merci

15
Giamma

J'avais les mêmes exigences d'avoir un projet source comprenant un projet de services Web Java ainsi qu'un projet angulaire (un projet basé sur angular-cli) et maven build devrait créer une guerre avec tous les fichiers angulaires qu'il contient. J'ai utilisé maven-frontend-plugin avec peu de changements de configuration pour le chemin de base.

Le but était de créer un fichier war contenant tout le code Java qu’il contenait, ainsi que tout le code angulaire compilé dans le dossier racine de war, le tout avec une seule commande mvn clean package

Une autre chose pour que tout cela fonctionne est d’éviter les conflits entre les URL de routeur d’applications angulaires et les URL de vos applications Java. Vous devez utiliser HashLocationStrategy. une façon de le configurer dans app.module.ts comme ci-dessous

app.module.ts - 

providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy },

]

La structure des dossiers pour Angular App est ci-dessous

projet angulaire

  • dist
  • e2e
  • node_modules
  • publique
  • src
    • app
    • les atouts
    • environnements
    • favicon.ico
    • index.html
    • main.ts
    • polyfills.ts
    • style.css
    • tsconfig.json
    • typings.d.ts
    • etc
  • tmp
  • .angular-cli.json
  • .gitignore
  • karma.conf.js
  • package.json
  • LISEZMOI.md
  • tslint.json
  • etc

Projet Maven -

  • src
    • principale
      • Java
      • ressources
      • webapp
        • WEB-INF
        • web.xml
  • angular-project (placez votre projet angulaire ici)
  • node_installation
  • pom.xml

Ajoutez la configuration de maven-frontend-plugin à pom.xml

 <properties>
    <angular.project.location>angular-project</angular.project.location>
    <angular.project.nodeinstallation>node_installation</angular.project.nodeinstallation>
</properties>

 <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.0</version>
            <configuration>
                <workingDirectory>${angular.project.location}</workingDirectory>
                <installDirectory>${angular.project.nodeinstallation}</installDirectory>
            </configuration>
            <executions>
                <!-- It will install nodejs and npm -->
                <execution>
                    <id>install node and npm</id>
                    <goals>
                        <goal>install-node-and-npm</goal>
                    </goals>
                    <configuration>
                        <nodeVersion>v6.10.0</nodeVersion>
                        <npmVersion>3.10.10</npmVersion>
                    </configuration>
                </execution>

                <!-- It will execute command "npm install" inside "/e2e-angular2" directory -->
                <execution>
                    <id>npm install</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                    <configuration>
                        <arguments>install</arguments>
                    </configuration>
                </execution>
                <!-- It will execute command "npm build" inside "/e2e-angular2" directory 
                    to clean and create "/dist" directory -->
                <execution>
                    <id>npm build</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                    <configuration>
                        <arguments>run build</arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <!-- Plugin to copy the content of /angular/dist/ directory to output 
            directory (ie/ /target/transactionManager-1.0/) -->
        <plugin>
            <groupId>org.Apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.4.2</version>
            <executions>
                <execution>
                    <id>default-copy-resources</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <overwrite>true</overwrite>
                        <!-- This folder is the folder where your angular files 
                        will be copied to. It must match the resulting war-file name.
                        So if you have customized the name of war-file for ex. as "app.war"
                        then below value should be ${project.build.directory}/app/ 
                        Value given below is as per default war-file name -->
                        <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}/</outputDirectory>
                        <resources>
                            <resource>
                                <directory>${project.basedir}/${angular.project.location}/dist</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Comme ci-dessus, appelez 'npm run build' en interne, assurez-vous que package.json doit avoir la commande build dans le script comme ci-dessous -

package.json

"scripts": {
    -----//-----,
    "build": "ng build --prod",
   -----//------
}

index.html devrait toujours être chargé quand quelqu'un frappe une application du navigateur, c'est pourquoi faites-en un fichier de bienvenue. Pour les services Web, disons que nous avons chemin/rest-services/* l'expliquerons plus tard.

web.xml - 

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

<servlet-mapping>
    <servlet-name>restservices</servlet-name>
    <url-pattern>/restservices/*</url-pattern>
</servlet-mapping>

La configuration ci-dessus est suffisante si votre application ne possède aucun chemin de contexte et est déployée sur le chemin racine du serveur. Mais si votre application possède un chemin de contexte tel que http: // localhost: 8080/myapplication/ , apportez également des modifications au fichier index.html - 

angular-project/src/index.html - Ici, document.location sera myapplication/(le chemin de contexte de votre application sinon/si l'application n'a pas de chemin de contexte)

Le but de faire du chemin de contexte un chemin de base pour angular-app est que chaque fois que vous effectuez un appel ajax http à partir d'angular, le chemin de base est préfixé à l'URL. Par exemple, si j'essaie d'appeler 'restservices/persons', il effectuera des appels vers ' http: // localhost: 8080/myapplication/restservices/persons '

index.html

 <!doctype html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>E2E</title>
   <script>document.write('<base href="' + document.location + '" />');     </script>

   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="icon" type="image/x-icon" href="favicon.ico">
 </head>
 <body>
   <app-root></app-root>
 </body>

Après tous les changements ci-dessus, une fois que vous avez exécuté mvn clean package, la guerre requise sera créée. Vérifiez si tout le contenu du dossier 'dist' angulaire est à la racine du fichier war.

21
TimeTraveler

J'ai un problème similaire: j'ai un module d'application Web maven nommé Tourism-Services contenant les services Web et un projet maven contenant le projet angular (j'ai créé le projet angular avec CLI dans le dossier src/main/angular5/tourism)

 enter image description here

contrairement à ce post et donc au lien suivant ( comment intégrer Angular 2 + Application Web Java Maven ) donné par Parth Ghiya, je pense que le projet angular devrait être placé dans le dossier webapp de Tourism-Services projet de module. Compte tenu de cela, j'ai d'autres questions:

  1. Normalement, tous les résultats de la compilation dans le dossier dist doivent être placés dans le dossier webapp. Mais dans le dossier dist, il n’ya pas toutes les ressources du projet angulaire (en tant qu’images, css qui devraient être présentes dans le dossier des ressources angulaires, ai-je raison?)

  2. Compte tenu des dépendances angulaires présentes dans node_modules, devrions-nous les intégrer également dans le dossier webapp? Il y a un obstacle: d'abord, il y a des fichiers TypeScript et devrait également être compilé pour être interprété par le serveur, mais peut-être sont-ils compilés et ajoutés lorsqu'ils sont importés dans les fichiers angulaires de l'application personnalisée? Quelle est la solution ?

  3. Devrions-nous inclure d'autres types de ressources provenant du projet angular dans le dossier webapp? (comme le dossier typings suggéré par Scrambo dans le lien ci-dessus)

0
flamant

J'ai essayé ces instructions et autres articles ... ceux-ci sont excellents mais c'est un peu ambigu. Donc, quelqu'un qui ne l'obtient pas immédiatement… vérifie ceci. 

GitHub

Suivez les instructions ci-dessous. 

  1. Ajoutez votre projet angulaire sous projet Java. Mon nom de projet angulaire est tdf project structure

2.open app.module.ts (dans votre projet angulaire/src/app/app.module.ts) Ajouter import et fournisseurs

import { LocationStrategy, HashLocationStrategy } from '../../node_modules/@angular/common';

      providers: [
        { provide: LocationStrategy, useClass: HashLocationStrategy },
      ],

3.open package.json (angularproject/package.json) Ajoutez "build": "ng build --prod" comme ci-dessous

{
  "name": "tdf",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
     **"build": "ng build --prod",** //change like this
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

4. mettre à jour votre pom.xml - ajouter forntend maven plugin - ajouter un répertoire de construction

      <project xmlns="http://maven.Apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.Apache.org/POM/4.0.0 http://maven.Apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>

          <groupId>angular</groupId>
          <artifactId>angular7Java</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <packaging>war</packaging>

          <name>angular7Java</name>
          <url>http://maven.Apache.org</url>

          <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>   
            **<angular.project.location>tdf</angular.project.location>**
            <!--your project name -->
            <angular.project.nodeinstallation>node_installation</angular.project.nodeinstallation>
          </properties>

          <dependencies>
            <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>3.8.1</version>
              <scope>test</scope>
            </dependency>
          </dependencies>

          <build>
           <plugins>    
                <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>1.6</version>
                        <configuration>
                        <workingDirectory>${angular.project.location}</workingDirectory>
                        <installDirectory>${angular.project.nodeinstallation}</installDirectory>
                         </configuration>
                        <executions>
                            <execution>
                                <id>install node and npm</id>
                                <goals>
                                    <goal>install-node-and-npm</goal>
                                </goals>
                                <configuration>
                                   <nodeVersion>v9.9.0</nodeVersion>
                                </configuration>
                            </execution>

                            <execution>
                                <id>npm install</id>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <!-- Optional configuration which provides for running any npm command -->
                                <configuration>
                                    <arguments>install</arguments>
                                </configuration>
                            </execution>

                             <execution>
                            <id>npm build</id>
                            <goals>
                                <goal>npm</goal>
                            </goals>
                            <configuration>
                                <arguments>run build</arguments>
                            </configuration>
                        </execution>

                        </executions>
                    </plugin>

                <!-- Plugin to copy the content of /angular/dist/ directory to output 
                    directory (ie/ /target/transactionManager-1.0/) -->
                <plugin>
                    <groupId>org.Apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.2</version>
                    <executions>
                        <execution>
                            <id>default-copy-resources</id>
                            <phase>process-resources</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <overwrite>true</overwrite>
                                <!-- This folder is the folder where your angular files 
                                will be copied to. It must match the resulting war-file name.
                                So if you have customized the name of war-file for ex. as "app.war"
                                then below value should be ${project.build.directory}/app/ 
                                Value given below is as per default war-file name -->
                                <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}/</outputDirectory>
                                <resources>
                                    <resource>
                                        <directory>${project.basedir}/${angular.project.location}/dist</directory>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
        <!--         <attachClasses>true</attachClasses>
                <webXml>target/web.xml</webXml>
                <webResources>
                    <resource>
                        <directory>src/main/webapp</directory>
                        <filtering>true</filtering>
                    </resource>
                </webResources> -->
            </configuration>
        </plugin>

                    <plugin>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.1</version>
                        <configuration>
                            <fork>true</fork>
                            <executable>C:\Program Files\Java\jdk1.8.0_181\bin\javac.exe</executable>

<!--make sure above directory is correct (make it same as your local javac.exe-->
                        </configuration>
                    </plugin>
            </plugins>
        </build>



        </project>

5 . Clic droit sur votre projet maven maven - installation maven Ou Terminal: mvn clean install

et attendez jusqu'à ce qu'il soit bloqué… une fois installé, vous pouvez voir que le dossier d'installation du noeud et le fichier war sont créés  enter image description here

0
Energy