gpt4 book ai didi

java - 将servlet添加到嵌入式tomcat

转载 作者:行者123 更新时间:2023-11-28 21:53:08 24 4
gpt4 key购买 nike

使用我的第一个嵌入式 tomcat 应用程序,所以这可能是一个简单的问题。

我已经创建了一个 servlet,我想用 Java 以编程方式将其添加到 Tomcat。我的驱动程序类如下所示:

    String contextPath = "/";
String appBase = ".";
Tomcat tomcat = new Tomcat();
tomcat.setPort(Integer.valueOf(port.orElse("8080") ));
Context ctx = tomcat.addContext(contextPath, appBase);
Tomcat.addServlet(ctx, "HelloWorldServlet", new HelloWorldServlet());

ctx.addServletMapping("/*", "HelloWorldServlet");

tomcat.start();
tomcat.getServer().await();

我的 servlet 具有以下定义。

 @WebServlet(
name = "HelloWorldServlet",
urlPatterns = {"/helloWorld"}
)

当我尝试运行它时,它告诉我我有一个

java.lang.illegalArgumentException: Main resource set specified [.......\target\tomcat.8080\webapps\.] is not valid.

我添加的 servlet 是否正确?基本上,我希望能够转到 localhost:8080/helloWorld 并让它触发我的 servlet。

最佳答案

我今天遇到了同样的问题:

嵌入式 Tomcat:

public class App 
{
public static void main( String[] args ) throws LifecycleException
{
int port = 8080;
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir("temp");
tomcat.setPort(port);

String contextPath = "/";
String docBase = new File(".").getAbsolutePath();

Context context = tomcat.addContext(contextPath, docBase);

HttpServlet servlet = new HelloWorldServlet();
String servletName = "HelloWorld";
String urlPattern = "/helloWorld";

tomcat.addServlet(contextPath, servletName, servlet);
context.addServletMappingDecoded(urlPattern, servletName);

tomcat.start();
tomcat.getServer().await();

}
}

我的小服务程序:

public class HelloWorldServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();

writer.println("Hello World!");

}

}

pom.xml

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<tomcat.version>8.0.48</tomcat.version>
</properties>

<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<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-jasper</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>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

关于java - 将servlet添加到嵌入式tomcat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com