将servlet添加到嵌入式tomcat

时间:2016-04-07 00:35:07

标签: java jsp tomcat servlets

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

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

    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。

1 个答案:

答案 0 :(得分:0)

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

嵌入式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>