java 将一个简单的 hello world servlet 编译成 tomcat 的 .war

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7924687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:02:28  来源:igfitidea点击:

Compiling a simple hello world servlet into a .war for tomcat

javatomcat

提问by Blankman

I'm doing some simple benchmarks, and I want to create a simple servlet that displays hello world, I have that part:

我正在做一些简单的基准测试,我想创建一个显示 hello world 的简单 servlet,我有那部分:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{ 
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException,IOException{
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  pw.println("<html>");
  pw.println("<head><title>Hello World</title></title>");
  pw.println("<body>");
  pw.println("<h1>Hello World</h1>");
  pw.println("</body></html>");
  }
}

Now I installed with the default installation of tomcat, in the folder:

现在我用tomcat的默认安装方式安装,在文件夹中:

.../libexec/webapps/ROOT

.../libexec/webapps/ROOT

I believe I have to drop a war file, is it possible to compile the above java class into a .war file w/o and editor using the command line only?

我相信我必须删除一个 war 文件,是否可以仅使用命令行将上述 java 类编译为 .war 文件,而无需和编辑器?

回答by Stephen Denne

A war file is simply a zip file, so with an appropriate directory structure and web.xml, you can create one with command line tools.

war 文件只是一个 zip 文件,因此通过适当的目录结构和 web.xml,您可以使用命令行工具创建一个。

The web.xml should contain at a minimum a way to direct your URL to your servlet.

web.xml 应至少包含将 URL 定向到 servlet 的方法。

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
  <servlet>
    <servlet-name>HelloWorldServlet</servlet-name>
    <servlet-class>HelloWorld</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

This web.xml should be in a folder named WEB-INFinside your war, and the compiled java class file should be in WEB-INF/classes

这个 web.xml 应该WEB-INF在你的 war 里面的文件夹中,编译的 java 类文件应该在WEB-INF/classes

The war file should be dropped in the webappsdirectory, not the ROOTdirectory.

War文件应该放在webapps目录中,而不是ROOT目录中。

Tomcat will find your war file, and unzip it.

Tomcat 会找到你的war 文件,并解压它。

If it was named "hello.war", the default context name would be "hello", and accessed at http://yourhost/hello/

如果它被命名为“hello.war”,则默认上下文名称将为“hello”,并在 http://yourhost/hello/