Java Web HelloWorld

本文讲描述如何不借助 IDE 写一个最最简单的 Java Web HelloWorld.

Java Web Application 的结构

  • /
    • WEB-INF
      • classes
      • lib
    • web.xml
    • (pages)

应用的根目录下包含 WEB-INF 目录和 web.xml 以及其他一些页面文件。WEB-INF 下包含 classes 和 lib 两个目录。此结构是一个约定,不能修改。

手工创建过程

假设 tomcat 目录是 {tomcat.home},本例使用的是 apache-tomcat-8.5.32

1. 进入 {tomcat.home}/webapps,并创建一个空目录

    $ cd {tomcat.home}/webapps
    $ mkdir helloworld

2. 进入 helloworld 目录再创建其他目录

    $ cd helloworld/
    $ mkdir WEB-INF
    $ mkdir -p WEB-INF/classes
    $ mkdir -p WEB-INF/lib

3. 创建 web.xml

这里直接从 tomat 自带示例中复制,然後删掉其中的内容,只剩下根元素即可。

    $ ls ../
    docs  examples  helloworld  host-manager  manager  ROOT
    $ cp ../examples/WEB-INF/web.xml WEB-INF/web.xml

web.xml 的内容经过删减後,只剩下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">
</web-app>

4. 创建供访问的页面

页面路径是 {tomcat.home}/helloworld.jsp

页面内容如下:

<html>
        <head>
                <title>HelloWorld</title>
        </head>
        <body>
                Hello, world!
        </body>
</html>

至此,这个手工项目就完成了。

5. 启动并访问

$ {tomcat.home}/bin/startup.sh

在浏览器中输入 http://localhost:8080/helloworld/helloworld.jsp 可查看效果。

HelloWorld Java Web Application