编译环境:MAC OS

编译servlet需要servlet API,但servlet API不是JDK的一部分。如果直接用javac去编译会报错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
classes javac HelloServlet.java 
HelloServlet.java:3: error: package javax.servlet does not exist
import javax.servlet.*;
^
HelloServlet.java:4: error: package javax.servlet.http does not exist
import javax.servlet.http.*;
^
HelloServlet.java:6: error: cannot find symbol
public class HelloServlet extends HttpServlet {
^
symbol: class HttpServlet
HelloServlet.java:8: error: cannot find symbol
public void doGet(HttpServletRequest request, HttpServletResponse response)
^
symbol: class HttpServletRequest
location: class HelloServlet
HelloServlet.java:8: error: cannot find symbol
public void doGet(HttpServletRequest request, HttpServletResponse response)
^
symbol: class HttpServletResponse
location: class HelloServlet
HelloServlet.java:9: error: cannot find symbol
throws IOException, ServletException {
^
symbol: class ServletException
location: class HelloServlet
HelloServlet.java:7: error: method does not override or implement a method from a supertype
@Override
^
7 errors

Tomcat提供了一个备份文件<TOMCAT_HOME>/lib/servlet-api.jar。在编译时候我们需要把这个JAR文件用-cp命令包含进来。

1
2
3
4
5
6
// Assume that Tomcat is installed in /Applications/tomcat
// Change directory to the source file
cd /Applications/tomcat/webapps/hello/WEB-INF/classes

// Compile
javac -cp .:/Applications/tomcat/lib/servlet-api.jar HelloServlet.java