1--用记事本新建一个servlet程序,文件名为HelloWorld.java,文件内容如下:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println ("<html><head><title>" ) ; out.println("This is my first Servlet"); out.println("</title></head><body>"); out.println("<h1>Hello,World!</h1>"); out.println("</body></html>"); } }
2--编译
将HelloWorld.java剪切到G:\apache-tomcat-6.0.39-windows-x86\apache-tomcat-6.0.39\common\classes 目
命令行方式下输入:
cd G:\apache-tomcat-6.0.39-windows-x86\apache-tomcat-6.0.39\common\classes
javac HelloWorld.java
用javac HelloWorld.java 来编译这个文件,如果出现无法import javax.servlet.*
则将G:\apache-tomcat-6.0.39-windows-x86\apache-tomcat-6.0.39\lib目录下的servlet-api.jar文件
添加到
C:\Program Files\Java\jre1.5.0_04\lib\ext目录中去就可以了
然后在G:\apache-tomcat-6.0.39-windows-x86\apache-tomcat-6.0.39\common\classes下会产生一个编译后
servlet文件:HelloWorld.class
3--实现
将HelloWorld.class拷贝到G:\apache-tomcat-6.0.39-windows-x86\apache-tomcat-6.0.39\webapps\zwjsapp1\INF\classes 目录下
其中classes 目录若没有就创建一个
用记事本打开G:\apache-tomcat-6.0.39-windows-x86\apache-tomcat-6.0.39\webapps\zwjsapp1\
INF\ 目录下面的
web.xml 如下所示,增加内容如下:
.
.
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>
修改后web.xml内容如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>
启动Tomcat,启动浏览器,输入http://localhost:8080/zwjsapp1/servlet/HelloWorld 如果看到输出HelloWorl
说明编写的servlet成功了。
注意:修改了web.xml 以及新加了class,都要重启Tomcat