Java + Maven + Tomcat intégré: Le projet refuse de reconnaître la page Web


J'ai essayé de faire de mon hôte d'application Java une page Web (une page HTML, pas JSP) via Apache Tomcat intégré dans l'application. J'utilise Maven pour le système de construction sur NetBeans IDE 8.0.2. Pour une raison quelconque, Tomcat refuse de reconnaître la page index.html que j'ai placée dans l'application malgré plusieurs tentatives et la création de toutes sortes de dossiers comme WEB-INF. Mais il me lance toujours une erreur 404.

Voici une partie du code pertinent que j'ai mis en place dans mon projet (certains codes ont été omis mais sans rapport avec la situation):

1. MainApplication.java-lance Tomcat

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
import java.util.Optional;
import org.apache.catalina.startup.Tomcat;

public class MainApplication{

    public static final Optional<String> port = Optional.ofNullable(System.getenv("PORT"));

    public static void main(String[] args) throws Exception {
        String contextPath = "/";
        String appBase = ".";
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(Integer.valueOf(port.orElse("8080")));
        tomcat.getHost().setAppBase(appBase);
        tomcat.addWebapp(contextPath, appBase);
        tomcat.start();
        tomcat.getServer().await();
    }
}

2. ShuttleServlet.java

@WebServlet(
            name = "ShuttleServlet", urlPatterns = {"/shuttle"}
    )

public class ShuttleServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Code to interact with application to be added later
    } 

3. Structure de répertoire

- src
|
 - main
 |
  - resources
  - webapp
  |
    * index.html
    * scripts.js

4. Pom Maven.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>com.example</groupId>
    <artifactId>TransportApp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-logging-juli</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper-el</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <tomcat.version>7.0.57</tomcat.version>
    </properties>
    <build>
  <finalName>TransportApp</finalName>
  <resources>
      <resource>
          <directory>src/main/webapp</directory>
          <targetPath>META-INF/resources</targetPath>
      </resource>
  </resources>
  <plugins>
      <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <inherited>true</inherited>
          <configuration>
              <source>1.8</source>
              <target>1.8</target>
          </configuration>          
      </plugin>      
      <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
              <descriptorRefs>
                  <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
              <finalName>TransportApp-${project.version}</finalName>
              <archive>
                  <manifest>
                      <mainClass>com.example.TransportApp.MainApplication</mainClass>
                  </manifest>
              </archive>
          </configuration>
          <executions>
              <execution>
                  <phase>package</phase>
                  <goals>
                      <goal>single</goal>
                  </goals>
              </execution>
          </executions>
      </plugin>     
  </plugins>
</build>            
</project>

5. Tomcat journaux de la console

Dec 04, 2016 3:09:24 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Dec 04, 2016 3:09:24 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Dec 04, 2016 3:09:24 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.57
Dec 04, 2016 3:09:24 AM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
INFO: No global web.xml found
Dec 04, 2016 3:09:25 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [170] milliseconds.
Dec 04, 2016 3:09:25 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]

Tous ces résultats dans un 404 qui a été persistant malgré plusieurs tentatives et dossiers maintenant supprimés. J'espère que tout cela aide à trouver le coupable.

Author: Casper Spruit, 2016-12-04

5 answers

Cause première du problème:

Le problème vient de votre classe Launcher. Dans la classe launcher, ci-dessous des lignes de code essayant de regarder dans le même répertoire pour l'application Web, ce qui n'est essentiellement pas correct.

 tomcat.addWebapp(contextPath, appBase);

Puisque appBase est défini sur ".", ce qui signifie qu'il va essayer de regarder dans le même répertoire où se trouve votre classe de lanceur.

Solution

Essayez d'utiliser le code ci-dessous, ce qui est assez simple à comprendre. Vous devez définir la webApp chemin d'accès correct au contexte tomcat pour le reconnaître lorsque vous atteignez ce chemin au moment de l'exécution.

    String webappDirLocation = "src/main/webapp/";
    Tomcat tomcat = new Tomcat();

    //The port that we should run on can be set into an environment variable
    //Look for that variable and default to 8080 if it isn't there.
    String webPort = System.getenv("PORT");
    if(webPort == null || webPort.isEmpty()) {
        webPort = "8080";
    }

    tomcat.setPort(Integer.valueOf(webPort));

    StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
    System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());

    // Declare an alternative location for your "WEB-INF/classes" dir
    // Servlet 3.0 annotation will work
    File additionWebInfClasses = new File("target/classes");
    WebResourceRoot resources = new StandardRoot(ctx);
    resources.addPreResources(new DirResourceSet(resources, "/WEB-     INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
    ctx.setResources(resources);

    tomcat.start();
    tomcat.getServer().await();
 2
Author: Birendra Singh Bisht, 2016-12-12 09:12:09

Le premier maven est ancien, utilisez Gradle à la place ;)

Chaque processus a un répertoire de travail, et quand un fichier est relatif, il sera interprété par rapport à cela. Ceci est important à comprendre, car à moins que vous ne l'utilisiez pour un test simple, la structure du répertoire peut être différente entre le développement et le déploiement.

Si vous construisez votre programme en tant que fichier jar, une URL relative comme "./src / main / webapp " ne fonctionnera probablement pas, car "src / main" disparaîtrait et seulement "webapp" serait laissé (comme lorsque vous construisez un fichier WAR).

Construire des outils comme Gradle (et Maven) et votreE a une étape "processResource" après la compilation, qui copie les ressources dans un emplacement qui fera (généralement) partie du chemin de classe. Étant donné que /main/resources/webapp ne sera pas copié à moins que vous ne construisiez une webapp, vous aurez des problèmes pour exécuter votre code en dehors de votreE.

Personnellement, je vous recommande de créer une application Spring boot, qui a déjà un tomcat. En Botte De Printemps .les fichiers html sont chargés à partir du chemin de classe (main/resources/static), et parce que les ressources sont à l'intérieur du chemin de classe, elles auront le même emplacement à la fois en développement et en déploiement (en raison du traitement des ressources).

Pour une application web spring boot, vous aurez besoin d'une dépendance org.springframework.démarrage: printemps-démarrage-démarreur-web: 1.4.1.PUBLIER Donc, votre construire.le fichier gradle ressemblerait à ceci (Vous pouvez créer un projet Gradle dans votre IDE)

apply plugin: 'java'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.4.1.RELEASE")
}

Votre main Java ressemblerait à ceci

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Mettez vous .fichier html dans / main / resources / static-TERMINÉ!! Comme vous pouvez probablement le deviner, il y a beaucoup de magie à l'intérieur de Spring boot, et la raison pour laquelle vous n'avez plus à écrire de code, c'est parce que l'équipe Spring Boot a choisi un très bon défaut, mais ne vous inquiétez pas si vous avez besoin d'être plus avancé plus tard, c'est Si vous avez besoin d'un rendu côté serveur vous pouvez ajouter org.springframework.boot: spring-boot-starter-thymeleaf: {version}, et mettez vos modèles dans / resources / templates et voilà.Il ya une tonne de bons tutoriels là-bas.

Spring a également une bien meilleure abstraction au-dessus des servlets appelés contrôleurs, encore une fois beaucoup de documentation.

 1
Author: Klaus Groenbaek, 2016-12-09 20:57:17

Essayez d'utiliser SpringBoot!!! qui a le tomcat intégré, utiliser la dépendance web et thymeleaf, thymeleaf est le moteur de template qui reconnaîtra votre page Web. essayez de créer un projet spring boot à partir de ce site http://start.spring.io / , qui est un initialiseur spring utilisé pour créer un projet maven avec spring boot. Ajoutez des dépendances web et thymeleaf et générez un projet. Importez le projet dans votreE en tant que projet maven, ou utilisez l'outil de ressort costume

DemoApplication.java

 @Controller
 @SpringBootApplication
 public class DemoApplication {
     public static void main(String[] args) {
         SpringApplication.run(DemoApplication.class, args);
     }  
     @RequestMapping(value = "/homepage" , method = RequestMethod.GET  )
     public String sample()
     {
         return "home";

     }
}

Pom.xml

   <?xml version="1.0" encoding="UTF-8"?>
   <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>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.7</java.version>
</properties>
<dependencies>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
    </build>
    </project>

Accueil.code html

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8"></meta>
 <title>HomePage</title>
 </head>
 <body>
 <h1>MY Spring Boot Home Page</h1>
 </body>
 </html>
 0
Author: Ezhil vikraman, 2016-12-13 22:49:29

Je pense que vous manquez la partie Nom d'hôte ainsi que les étapes de construction par maven.Essayez de vous exécuter avec les commandes maven et les commandes java-jar. Essayez avec voir les travaux suivants ou non.

 public static final Optional<String> PORT = Optional.ofNullable(System.getenv("PORT"));
public static final Optional<String> HOSTNAME = Optional.ofNullable(System.getenv("HOSTNAME"));

public static void main(String[] args) throws Exception {
    String contextPath = "/" ;
    String appBase = ".";
    Tomcat tomcat = new Tomcat();   
    tomcat.setPort(Integer.valueOf(PORT.orElse("8080") ));
    tomcat.setHostname(HOSTNAME.orElse("localhost"));
    tomcat.getHost().setAppBase(appBase);
    tomcat.addWebapp(contextPath, appBase);
    tomcat.start();
    tomcat.getServer().await();
}

Suivez ces étapes : (vous devez avoir maven installé localement) Ouvrez cmd, allez dans le dossier source, où le fichier pom is.Do commandes suivantes

Compilation Mvn

Puis appuyez sur entrée

Paquet Mvn.

Puis appuyez sur entrée

Cible Cd puis appuyez sur entrée

Java-jar [nom de votre application].jar (Dans le dossier cible, vous verrez un fichier jar, mettez son nom ici)

Une fois que vous exécutez à partir de la commande, vous pourrez naviguer par localhost dans le navigateur. Netbeans exécuter m'a donné 404. je l'ai résolu de cette façon.

Vous pouvez vérifier que ce lien exécute la partie Application Web: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/basic_app_embedded_tomcat/basic_app-tomcat-embedded.html

 0
Author: Ahmed Raaj, 2016-12-14 08:08:37

Je ne sais pas si vous avez résolu le problème décrit ici. J'espère que cela aidera d'autres. Pour intégrer Tomcat, j'ai utilisé un plugin plutôt que des dépendances: donc, on n'a pas besoin d'une classe principale et du code pour créer une instance tomcat.
Voici ce que le POM doit inclure:

<project ...>
  .....
  <dependencies>
    <!-- no need of any --->
  </dependencies>
  <build>
     <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>                    
                <server>localhost</server>
                <path>/${project.build.finalName}</path>
            </configuration>
        </plugin>

    </plugins>
  </build>
</project>

Voici un exemple de web.xml

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


   <display-name>My Test App</display-name>
   <description>A test app</description>

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

   <session-config>
     <session-timeout>30</session-timeout>
   </session-config>
</web-app>

Vous n'avez besoin ni d'une classe principale ni du code à l'intérieur (comme dans la question). Nous avons bien sûr besoin de pages à afficher, alors voici un exemple de l'index.HTML (comme indiqué dans le web.xml):

<html>
   <body>
      <h2>Hello World!</h2>
   </body>
</html>

Dans eclipse: faites un clic droit, exécutez comme "exécuter les configuratuions", sous "Maven Build" ajoutez une "Nouvelle configuration de lancement", définissez le répertoire de base et entrez sous "Objectifs": tomcat7:exécuter. Ça y est! Vous obtiendrez:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] --------------------------------------------------------------------
[INFO] Building rest-with-jersey Maven Webapp 0.0.1-SNAPSHOT
[INFO] --------------------------------------------------------------------
[INFO] 
[INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) > process-classes @ rest-with-jersey >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ rest-with-jersey ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ rest-with-jersey ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) < process-classes @ rest-with-jersey <<<
[INFO] 
[INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ rest-with-jersey ---
[INFO] Running war on http://localhost:8080/rest-with-jersey
[INFO] Using existing Tomcat server configuration at /common/home/$$$/$$$$/lnx/workspace/rest-with-jersey/target/tomcat
[INFO] create webapp with contextPath: /rest-with-jersey
Sep 11, 2017 4:03:07 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 11, 2017 4:03:07 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Sep 11, 2017 4:03:07 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Sep 11, 2017 4:03:09 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]

In a browser with http://localhost:8080/rest-with-jersey/ you get the " Hello World!". 
 0
Author: Meziane, 2017-09-11 14:19:20