Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java+;Maven+;嵌入式Tomcat:项目拒绝识别网页_Java_Html_Tomcat_Http Status Code 404_Embedded Tomcat 7 - Fatal编程技术网

Java+;Maven+;嵌入式Tomcat:项目拒绝识别网页

Java+;Maven+;嵌入式Tomcat:项目拒绝识别网页,java,html,tomcat,http-status-code-404,embedded-tomcat-7,Java,Html,Tomcat,Http Status Code 404,Embedded Tomcat 7,我一直试图通过应用程序中嵌入的apachetomcat使我的Java应用程序承载一个web页面(一个HTML页面,而不是JSP)。我在NetBeans IDE 8.0.2上使用Maven构建系统。出于某种原因,Tomcat拒绝识别我在应用程序中放置的index.html页面,尽管我多次尝试并创建了各种文件夹,如WEB-INF。但它仍然向我抛出了一个404错误 以下是我在项目中设置的一些相关代码(一些代码被省略,但与实际情况无关): 一,。java-启动Tomcat 三,。目录结构 四,。Mave

我一直试图通过应用程序中嵌入的
apachetomcat
使我的Java应用程序承载一个web页面(一个HTML页面,而不是JSP)。我在
NetBeans IDE 8.0.2上使用
Maven
构建系统。
出于某种原因,
Tomcat
拒绝识别我在应用程序中放置的
index.html
页面,尽管我多次尝试并创建了各种文件夹,如
WEB-INF
。但它仍然向我抛出了一个
404
错误

以下是我在项目中设置的一些相关代码(一些代码被省略,但与实际情况无关):

一,。java-启动Tomcat

三,。目录结构

四,。Maven pom.xml


所有这些都会导致一个
404
,尽管多次尝试,该文件夹仍然保持不变,现在已被删除。我希望所有这些都有助于找到罪魁祸首。

第一个maven已经老了,改用Gradle;)

每个进程都有一个工作目录,当一个文件是相对的时,它将被解释为与之相关。 理解这一点很重要,因为除非您将其用于简单的测试,否则开发和部署之间的目录结构可能不同

如果将程序构建为jar文件,则像“/src/main/webapp”这样的相对URL很可能无法工作,因为“src/main”将消失,只剩下“webapp”(就像构建WAR文件一样)

像Gradle(和Maven)这样的构建工具,您的IDE在编译之后有一个“processResource”步骤,它将资源复制到(通常)成为类路径一部分的位置。由于除非您正在构建webapp,否则不会复制/main/resources/webapp,因此在IDE之外运行代码时会出现问题

就我个人而言,我建议您构建一个SpringBoot应用程序,它已经有了一个嵌入式tomcat。在Spring Boot中,html文件是从类路径(main/resources/static)加载的,因为资源在类路径中,所以它们在开发和部署中的位置相同(因为资源处理)

对于SpringBootWeb应用程序,您需要一个依赖项 org.springframework.boot:springbootstarterweb:1.4.1.RELEASE 因此build.gradle文件如下所示(您可以在IDE中创建一个gradle项目)

您的Java Main将如下所示

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);
    }
}
将.html文件放在/main/resources/static-DONE!! 正如您可能猜到的,Spring boot中有很多神奇的东西,您不必再编写任何代码的原因是因为Spring boot团队选择了非常好的默认值,但是如果您以后需要更高级,请不要担心,这也是可能的。如果您需要服务器端呈现,您可以添加org.springframework.boot:springboot starter thymeleaf:{version},然后将模板放入/resources/templates中,就可以了。有很多很好的教程


Spring在名为控制器的servlet之上还有一个更好的抽象,同样还有很多文档。

尝试使用SpringBoot!!!其中嵌入了tomcat, 使用web和EleAF依赖项, thymeleaf是一个模板引擎,可以识别您的网页。 尝试从这个网站创建一个springboot项目,它是一个spring初始值设定项,用于使用springboot创建maven项目。添加web和EleAF依赖项并生成项目。 将IDE中的项目作为maven项目导入, 或使用弹簧工具套装

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>

4.0.0
com.example
演示
0.0.1-快照
罐子
演示
SpringBoot的演示项目
org.springframework.boot
spring启动程序父级
1.4.2.1发布
UTF-8
UTF-8
1.7
org.springframework.boot
弹簧启动装置
org.springframework.boot
SpringBootStarterWeb
org.springframework.boot
弹簧起动试验
测试
org.springframework.boot
springbootmaven插件
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>

主页
我的春靴主页

问题的根本原因:

问题在于你的Launcher类。在launcher类中,下面的代码行试图查找web应用程序的同一目录,这基本上是不正确的

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

我认为您缺少主机名部分以及maven的构建步骤。请尝试使用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();
}
publicstaticfinaloptionalport=Optional.ofNullable(System.getenv(“PORT”));
public static final Optional HOSTNAME=Optional.ofNullable(System.getenv(“HOSTNAME”);
公共静态void main(字符串[]args)引发异常{
字符串contextPath=“/”;
字符串appBase=“.”;
Tomcat Tomcat=新的Tomcat();
setPort(Integer.valueOf(PORT.orElse(“8080”));
setHostname(HOSTNAME.orElse(“localhost”));
tomcat.getHost().setAppBase(appBase);
addWebapp(contextPath,appBase);
tomcat.start();
tomcat.getServer().await();
}
遵循以下步骤:(您需要在本地安装maven) 打开cmd,转到pom文件所在的源文件夹。执行以下命令

mvn编译

然后按回车键

mvn包

然后按回车键

cd目标 然后按回车键

java-jar[your app name].jar(在目标文件夹中,您将看到一个jar文件,将其名称放在这里)

一旦你从通信中运行
 @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";

     }
}
   <?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>
 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8"></meta>
 <title>HomePage</title>
 </head>
 <body>
 <h1>MY Spring Boot Home Page</h1>
 </body>
 </html>
 tomcat.addWebapp(contextPath, appBase);
    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();
 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();
}
<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-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>
<html>
   <body>
      <h2>Hello World!</h2>
   </body>
</html>
[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!".