先看下目录结构:
(该目录在tomcat/webapps/下面,ch1是项目名)
├───ch1
│ └───WEB-INF
│ │ web.xml
│ │
│ └───classes
│ Ch1Servlet.class
1.2web.xml
<?xml version="1.0" encoding="utf-8" ?>
<web-app xmlns="http:/java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>Chapter1 Servlet</servlet-name>
<servlet-class>Ch1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Chapter1 Servlet</servlet-name>
<url-pattern>/time</url-pattern>
</servlet-mapping>
</web-app>
2.3 Ch1Servlet.java
(Ch1Servlet.class 是由Ch1Servlet.java 编译而来的)
(编译命令:javac -class d: omcatlibServlet-api.jar -d classes src/Ch1Servlet.java)
(这条命令会在当前目录classes文件夹下生成Ch1Servlet.class)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Ch1Servlet extends HttpServlet {
public void doGet(HttpServletRequest reque, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
java.util.Date today = new java.util.Date();
out.println("<html>" +
"<body>" +
"<h1 align=center>HF's chapter1</h1>" +
"<br>" + today + "</body></html>");
}
}
2.4 启动并访问 localhost:8088/ch1/time
端口是你tomat配置文件中设置的。
ch1 是你在tomcat/webapps中创建的项目文件夹名。
time 是你在web.xml中指定的访问路径。