2016-12-03 9 views
4

アプリケーションにApache Tomcatが埋め込まれたJavaアプリケーションホストをWebページ(JSPではなくHTMLページ)にしようとしています。私がMavenをビルドシステムに使用していますNetBeans IDE 8.0.2.何らかの理由でTomcatindex.htmlページの認識を拒否しました。複数の試行にもかかわらず、WEB-INFのようなすべての種類のフォルダを作成してもアプリケーションに配置しました。しかしそれはまだ私に404エラーを投げます。 - TomcatのJava + Maven + Embedded Tomcat:Webページの認識を拒否する

アップ火災

1. MainApplication.java:ここ

は、私は私のプロジェクトに設定しているとして、関連するコードの一部(いくつかのコードは、状況に省略しますが、無関係されています)です

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.ディレクトリ構造

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

4. Mavenのの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>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のコンソールログ

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

404におけるこれらの結果のすべてのこと複数の試行と今削除されたフォルダにもかかわらず永続化されています。私はこのすべてが犯人を見つけるのに役立つことを願っています。

答えて

1

まずMavenのではなく、Gradleのを使用し、古いです;)

各プロセスには、作業ディレクトリがあり、ファイルが相対的であるときには、それに関連して解釈されます。 これは、単純なテストにこれを使用しない限り、ディレクトリ構造が開発と展開の間で異なる可能性があるため、理解することが重要です。

プログラムをjarファイルとしてビルドすると、 "src/main"が消えて "webapp"だけが残るため、 "./src/main/webapp"のような相対URLはほとんど機能しませんWARファイルを作成するとき)。

Gradle(やMaven)やIDEのようなビルドツールは、コンパイル後に(通常は)クラスパスに含まれる場所にリソースをコピーする「processResource」ステップを持っています。 Webアプリケーションをビルドしない限り、/ main/resources/webappはコピーされないため、IDEの外部でコードを実行する際に問題が発生します。

個人的には、既に埋め込みの風袋を持っているSpringブートアプリケーションを構築することをお勧めします。 Springブートでは、.htmlファイルはクラスパス(main/resources/static)からロードされ、リソースはクラスパス内にあるため、(リソース処理のために)開発とデプロイの両方で同じ場所になります。

春ブーツのWebアプリのためには、1つの依存関係 org.springframework.boot必要があります。春ブート・スターター・ウェブ:だから1.4.1.RELEASE あなたビルドを。Gradleではファイルは、Javaのメインはこの

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); 
    } 
} 

ようになり

apply plugin: 'java' 
sourceCompatibility = 1.8 

repositories { 
    mavenCentral() 
} 

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

(あなたはあなたのIDEでGradleのプロジェクトを作成することができます)、次のようになり/あなたは/メイン/リソースをで.htmlファイルに入れ静的 - 完了! あなたはおそらく、春のブートの中にたくさんの魔法があると推測できます。なぜなら、春のブートチームが非常に良いデフォルトを選んだからです。あなたが必要であれば心配する必要はありません後でさらに高度化することも可能です。サーバサイドのレンダリングが必要な場合は、org.springframework.bootを追加することができます:spring-boot-starter-thymeleaf:{バージョン}、テンプレートを/ resources/templatesに入れてください。そこにはたくさんの良いチュートリアルがあります。

Springには、コントローラと呼ばれるサーブレットの上にはるかに優れた抽象化があり、さらに多くのドキュメントがあります。

+0

彼は、スタンドアロンについて尋ねたのMavenとTomcatを埋め込む際に、なぜあなたは、いくつかのGradle +春のブートコードと答えるでしょうか? –

0

SpringBootを使用してください! webとthymeleafの依存関係を使用する thymeleafはあなたのWebページを認識するテンプレートエンジンです。 このウェブサイトhttp://start.spring.io/からスプリングブートプロジェクトを作成しようとします。これはスプリングブートを使用してmavenプロジェクトを作成するために使用されるスプリングイニシャライザです。 WebとThymeleafの依存関係を追加し、プロジェクトを生成します。 インポートMavenプロジェクトとしてあなたのIDEでプロジェクト、 やSpringツールのスーツを使用

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> 

home.html

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"></meta> 
<title>HomePage</title> 
</head> 
<body> 
<h1>MY Spring Boot Home Page</h1> 
</body> 
</html> 
+1

あなたのhtmlファイルを表示するソリューションは、3つの新しいライブラリを含み、アプリケーション全体を再構築することですか? – zack6849

1

問題の根本原因:

Launcherクラスに問題があります。ランチャークラスでは、web-appと同じディレクトリを検索しようとするコード行の下にありますが、これは本質的に正しくありません。

tomcat.addWebapp(contextPath, appBase); 

appBaseが "。"に設定されているため、ランチャークラスと同じディレクトリを検索しようとします。

ソリューション

は理解する単純明快である、コードの下に使用してみてください。実行時にそのパスにヒットしたときに認識するためには、webAppパスをtomcatコンテキストに正しく設定する必要があります。

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(); 
0

私は、あなたがホスト名の部分だけでなく、ビルドの手順をmaven.Try mavenコマンドとjava -jarコマンドで実行することができないと思う。次の作品を見てみてください。

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(); 
} 

この手順をFolow:(あなたはMavenのは、ローカルにインストールしておく必要があります) オープンCMD、POMファイルがあるソースフォルダに移動します。次のコマンド

MVN

をコンパイルするには、その後

MVNパッケージを入力して押してください。

はその後、その後(ターゲットフォルダで使用すると、jarファイルが表示され、ここでその名を置くの.jar [アプリ名] -jar

javaのEnterキーを押し

CDターゲット を入力押します)

コマンドから実行すると、ブラウザでlocalhostを参照できるようになります。Netbeansを実行すると404が表示されました。この方法で解決しました。

あなたは、Webアプリケーションパートを実行し、このリンクの確認することができます:あなたはここで説明する問題を解決した場合、私は知らない http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/basic_app_embedded_tomcat/basic_app-tomcat-embedded.html

0

を。 これが他の人に役立つことを願っています。 Tomcatを埋め込むために、私は依存関係ではなくプラグインを使用しました。こうすることで、メインクラスとコードでTomcatインスタンスを作成する必要はありません。ここ
はPOMが含まれている必要がありますものです:ここでは

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

は、あなたが問題のように、メインクラスにも内部コード(どちらも必要ありません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> 

の一例です)。 Eclipseで

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

::私たちは、もちろんので、ここで、表示するページが必要なのですか はindex.htmlを(web.xmlに述べたように)の一例である右クリックし、「実行configuratuions」として実行します"Maven Build"の下に "New launch configuration"を追加し、Baseディレクトリを設定し、 "Goals"の下に「tomcat7:run」と入力します。 ThaT's it! あなたが得るもの:

[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!". 
関連する問題