1

作为一个新手,我创建了一个 HelloWorld servlet:

package com.rx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/helloworld")
public class HelloWorld extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter writer = response.getWriter();
    writer.write("<html><body>Hello World</body</html>");
  }
}

然后我的pom.xml中有如下配置:

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>rx.helloworld</groupId>
<artifactId>simpleservlet</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>simpleservlet Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<war.name>simpleservlet</war.name>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<servlet.version>4.0.1</servlet.version>
</properties>
<dependencies>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>${servlet.version}</version>
  <scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${war.name}</finalName><!-- name of the bundled project when it is finally built -->
<plugins>
    <plugin>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-maven-plugin</artifactId>
      <version>9.3.9.v20160517</version>
      <configuration>
        <httpConnector>
          <!--host>localhost</host-->
        </httpConnector>
      </configuration>
    </plugin>
</plugins>
</build>
</project>

我从 servlet 规范文档中读到,其中告诉

如果 Web 应用程序不包含任何 Servlet、Filter 或 Listener 组件,或者使用注释来声明它们,则它不需要包含 web.xml。换句话说,仅包含静态文件或 JSP 页面的应用程序不需要存在 web.xml。

我确实用过@WebServlet,所以没有包含web.xml

完整的代码库在这里

问题:但是当我尝试使用带有命令的码头mvn jetty:run运行它时,我根本找不到我的 servlet。如何解决这个问题?

4

1 回答 1

1

最终自己想通了,说它错过了maven-war-plugin中的一个配置:

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
            <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
</plugin>

failOnMissingWebXml应该配置,false不是默认值

于 2019-03-08T19:46:31.133 回答