FirstServlet目录结构为:
FirstServlet
| ---- index.html
| ---- WEB-INF
| ---- classes
| ---- FirstServlet.java
| ---- edu.servlet.FirstServlet.class
| ---- lib
| ---- web.xml
如图:
(2)在classes目录下编写FirstServlet.java,其内容为:
package edu.servlet;
import java.io.*;
import javax.servlet.*;
public class FirstServlet extends GenericServlet
{
public FirstServlet(){
System.out.println("我被实例化了!");
}
public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException{
String data = "hello servlet!";
OutputStream out = res.getOutputStream();
out.write(data.getBytes());
}
public void init(ServletConfig config)throws ServletException{
System.out.println("我被初始化了!");
}
}
(3)在cmd窗口中编译FirstServlet.java(因为带有报名,所以应该使用javac -d . FirstServlet.java)
但是会报错,因为classpath路径下没有servlet相关的jar包,所以编译不成功,解决办法:
set classpath = %classpath%;C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar(因为tomcat\lib下有servlet的jar包)
然后再执行javac -d . FirstServlet.java,则会编译成功!
(4)在web.xml中编写servlet的映射文件
<servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>edu.servlet.FirstServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/first.do</url-pattern>
</servlet-mapping>
(5)启动tomcat,会发现启动的时候打印出"我被实例化了!""我被初始化了!",因为web.xml文件中设置<load-on-startup>0</load-on-startup>
(6)地址栏上输入:http://localhost:8080/FirstServlet/first.do则可以出现: