一、Servlet类:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Hello_servlet implements Servlet {
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destory it");
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init it");
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("servlet service");
PrintWriter pw = res.getWriter();
pw.print("Hello world");
}
}
二、该Servlet的配置文件
<!--servlet build start-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.servlet.Hello_servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/sp</url-pattern>
</servlet-mapping>
<!--servlet build end-->
三、启动Tomcat
四、地址栏输入:http://127.0.0.1:8080/myWebSite/sp 看到输出Hello world即为正确
*出现的问题:<servlet-class>com.servlet.Hello_servlet</servlet-class>。此处应该是包名+类名,我的包名是com.servlet,类名为Hello_servlet。
*关于目录层次问题:apache-tomcat-6.0.43\webapps\myWebSite\WEB-INF\com\servlet\Hello_servlet.class。注意经试验此处只要有.class类文件就可以了,不必有.java源文件