使用我的第一个嵌入式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();
}
}
我的Servlet:
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>