有誰說了編寫Servlet必須繼承自HttpServlet類,必須實現doGet)或者doPost) ,難道實現Servlet接口就不行了嗎?
其實編寫Servlet主要有三種方法,一是實現Servlet接口,二是繼承抽象類GenericServlet,三是繼承HttpServlet類。下面分別用這三種方法去實現Servlet:
一)要從實現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類中只有一個抽象方法,即serviceServletRequest 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>");
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- doGet(request, response);
- }
- }