如何激活一个HttpServlet class?

How to activate a HttpServlet class?

我有一个 class 扩展到 HttpServlet class。

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

public class GreetServer extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("hello client");
    }

    // Method to handle POST method request.
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doGet(request, response);
    }
}

我的问题是,如何让它工作并处理 POST 和 GET 请求(我应该在 public static void main(String[] args) 方法中写什么)? 我正在使用 Heroku 来部署应用程序。 提前致谢。

A Servlet cannot stand alone. You need a web container 托管您的 Servlet。

“Servlet”中的“-let”表示这是服务器应用程序的一小部分。服务器应用程序的大部分工作,例如侦听 port for incoming connections, performing initial analysis of each incoming request、调度到特定的 Servlet,以及通过网络将 Servlet 的响应发回,都是由托管 Servlet 的 Servlet 容器执行的。

换句话说,您的 Servlet 是一个小组件,可以插入一个更大的 Servlet 容器服务器基础设施应用程序,该应用程序 运行 在 Java implementation 之上(从供应商处获得,例如 Pivotal , Amazon, Oracle, BellSoft, Azul Systems, Red Hat/IBM, Adoptium, Microsoft, etc.) 运行s 在主机操作系统 (OS)(例如 macOS、Linux、BSD、MS Windows 等)。

Jakarta Servlet
server stack
your Servlet
Servlet container (Tomcat/Jetty etc.)
Java
host operating system
computer hardware

作为初学者,我建议使用 Apache Tomcat or Eclipse Jetty as your Servlet container. These two products are relatively small and simple, implementing only a handful of the few dozen Jakarta specifications.

稍后,如果您的 Web 应用发展到可以利用 other Jakarta specs not supported by Tomcat/Jetty, you can either add Jakarta implementation libraries to Tomcat/Jetty, or you may choose to move to a larger server that comes bundled with those libraries. Examples include TomEE, Payara, WildFly/JBoss, Open Liberty/WebSphere 等。

我还建议你在编程的同时多做一些学习。从 Wikipedia page.

开始

将 Servlet 部署到 Web 容器的常用方法是将编译后的 class(es) 打包到 WAR 文件中。然后只需将该文件放入特定容器服务器的相应文件夹中。

在开发过程中,您的 IDE(例如 IntelliJ、NetBeans 或 Eclipse)可能可以 运行 自身内部的 Servlet 容器或可以连接到外部-运行宁 Servlet 容器。例如,某些 Maven 原型将在您的 IDE 中以嵌入式模式包含 运行ning Jetty 的操作,以便快速方便地执行您正在开发的 Servlet。

在您的特定情况下,您说要使用 Heroku 进行生产。 Heroku 是一家云服务公司,提供 Servlet 服务器堆栈,您将在其上部署 Servlet,您的 WAR 文件。

在开发 Servlet 时,您可以 运行 使用 Tomcat 或 Jetty 等产品,稍后您可以部署到 Heroku。 Jakarta Servlet being an open specification 的全部要点是您编写的任何 Servlet 都应该 运行 在符合该规范的任何和所有 Servlet 容器上成功。

您问的是:

What should I write in my public static void main(String[] args) method

Servlet 没有 main 方法。

Servlet 容器自动定位、加载、实例化和初始化您的 servlet。当对 Web 应用程序的请求到达服务器时,Web 容器会自动调用 Servlet 对象上的方法。