hooyes

最简单的第一个Servlet

|2020-05-01

请尊重原创,本文原文地址:https://hooyes.net/p/first-servlet

Servlet 是Java类,实现了HttpServlet接口,用于服务HTTP请求。 我将仅使用文本工具和命令行(不需要任何IDE)生成一个最简单的Servlet。

先简单介绍一下本文基于的开发环境

$ java -version
java version "14.0.1" 2020-04-14
Java(TM) SE Runtime Environment (build 14.0.1+7)
Java HotSpot(TM) 64-Bit Server VM (build 14.0.1+7, mixed mode, sharing)
$ javac -version
javac 14.0.1
$ catalina version
Using CATALINA_BASE:   /usr/local/Cellar/tomcat/9.0.34/libexec
Server version: Apache Tomcat/9.0.34
OS Name:        Mac OS X
OS Version:     10.14.5
Architecture:   x86_64
JVM Version:    13.0.2+8
......

Tomcat Web 配置

根目录:/usr/local/Cellar/tomcat/9.0.34/libexec/webapps/ROOT 以下简称: {WEB根目录}

端口:8080

以下正式开始,我们的目标就是将 HelloHooyes.java 编译成字节码 HelloHooyes.class ,然后将 HelloHooyes.class 布署到 Tomcat 上运行。通过浏览器Get请求输出 “Hello Hooyes!”

1、创建一个文件 HelloHooyes.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloHooyes extends HttpServlet {
   protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
      res.getWriter().append("Hello Hooyes!");
   }

   protected void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
      res.getWriter().append("Welcome to https://hooyes.net/p/first-servlet");
   }
}

github上的 HelloHooyes.java

2、编译Servlet

命令行进入 HelloHooyes.java 所在的目录,执行javac编译:

javac -cp .:/usr/local/Cellar/tomcat/9.0.34/libexec/lib/servlet-api.jar --release 13 HelloHooyes.java

javac 参数说明

-cp .:/usr/local/Cellar/tomcat/9.0.34/libexec/lib/servlet-api.jar 根据具体的Tomcat目录确定

release 13 因为本机JVM Version: 13

编译成功后,将在同一目录生成 HelloHooyes.class

3、布署Servlet

{WEB根目录}/WEB-INF 中的 web.xml 添加配置

<servlet>
   <servlet-name>hooyes</servlet-name>
   <servlet-class>HelloHooyes</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>hooyes</servlet-name>
   <url-pattern>/HelloHooyes</url-pattern>
</servlet-mapping>

HelloHooyes.class 放到 {WEB根目录}/WEB-INF/classes 目录中

4、测试

http://localhost:8080/HelloHooyes

如果你遇到问题,可以在github上给我提一个 issue.

https://hooyes.net/p/first-servlet
https://hooyes.net/p/first-servlet
$ welcome to hooyes.net
[INFO] ------------------------------o-
[INFO] Author : HOOYES
[INFO] Site : https://hooyes.net
[INFO] Page : https://hooyes.net/p/first-servlet
[INFO] Last build : 2023-07-31 09:16:20 +0000
[INFO] -0------------------------------
原文地址:https://hooyes.net/p/first-servlet
原文地址:https://hooyes.net/p/first-servlet

...

Content
...
TOP