首相要配置Sevelet编译环境
方法:
sun下载javax.servlet.jar放在%JAVA_HOME%/lib/ 目录下
编辑环境变量
CLASSPATH 追加如下值 %JAVA_HOME%/lib/javax.servlet.jar
Hello.java
package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class Hello extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>Sample Application Servlet Page</title>");
writer.println("</head>");
writer.println("<body bgcolor=white>");
writer.println("<table border=\"0\">");
writer.println("<tr>");
writer.println("<td>");
writer.println("<img src=\"images/tomcat.gif\">");
writer.println("</td>");
writer.println("<td>");
writer.println("<h1>Sample Application Servlet</h1>");
writer.println("This is the output of a servlet that is part of");
writer.println("the Hello, World application.");
writer.println("</td>");
writer.println("</tr>");
writer.println("</table>");
writer.println("<br><br><p>yun test servlet</p>");
writer.println("</body>");
writer.println("</html>");
}
}
编译Hello.java 得到Hello.java
创建一个web应用项目helloservlet
在WEB-INF目录下创建web.xml文件及classes/test目录
将Hello.class复制到WEB-INF/test/目录下
web.xml代码
<?xml version="1.0" encoding="ISO-8859-1"?>
<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">
<display-name>Hello, World Application</display-name>
<description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description>
<servlet>
<servlet-name>myownserv</servlet-name>
<servlet-class>test.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myownserv</servlet-name>
<url-pattern>/testmyown</url-pattern>
</servlet-mapping>
</web-app>
通过http://localhost:8080/helloservlet/testmyown就可访问servlet了