编写Servlet主要有三种方法,一是实现Servlet接口,二是继承抽象类GenericServlet,三是继承HttpServlet类。
(一)要从实现Servlet接口来编写Servlet是比较麻烦的,因为必须实现Servlet接口中的所有方法,Servlet接口主要定义了五个方法,它们分别为:
(1)void init(ServletConfig config) throws ServletException
(2)ServletConfig getServletConfig()
(3)void service(ServletRequest req,ervletResponse res) throws ServletException,IOException
(4)String getServletInfo()
(5)void destroy()
下面用实现Servlet接口的方法编写Servlet:
import javax.servlet.*;
import java.io.*;
public class TestServlet implements Servlet{
public void init(ServletConfig config) throws ServletException{
System.out.println("init");
}
public ServletConfig getServletConfig(){
reture null;
}
public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException{
//这里可以实现请求后要做的内容
PrintWriter out = response.getWriter();
out.println("Hello World!");
}
public String getServletInfo(){
return null;
}
public void destroy(){
System.out.println("destory");
}
}
(二)继承抽象类GenericServlet编写Serlvet,这个相对比实现Servlet接口要容易一点,GenericServlet类中只有一个抽象方法,即service(ServletRequest req, ServletResponse res),只要实现这个方法就行了,下面看例子:
import javax.servlet.*;
import java.io.IOException;
public TestGenericServlet extends GenericServlet{
public abstract void service(ServletRequest req,ServletResponse res)throws ServletException,IOException{
PrintWriter out = response.getWriter();
out.println("Hello World!");
}
}
(3)继承HttpServlet类编写Servlet应该是最容易的,而且是最常见的,我们一般要编写Servlet直接继承这个类就行了,重写 doGet()或者doPost()方法即可,下面看例子:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public TestHttpServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>HelloWorld</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("<hr>");
out.println("HelloWorld");
out.println("</body></html>");
}
}