HttpServlet的Service方法到底是怎么回事?
馬克-to-win:談到doGet,很多同學(xué)心中可能有疑問,為什么html的用戶的GET的請求,會被Servlet的doGet方法處理呢?這就談到了HttpServlet的Service方法。它的功能就是調(diào)用與HTTP請求的方法相對應(yīng)的do功能。例如,如果HTTP請求方法為GET,則調(diào)用doGet() 。這樣作為Servlet編寫者的你,只需覆蓋doGet方法。這也是我們迄今為止的做法。有意思的是,假如用戶有Get請求,但我們沒有覆蓋doGet的方法,會怎么樣?HttpServlet的Service方法就會調(diào)用 HttpServlet的doGet方法,那個doGet方法什么也不做,所以也不會報錯。(這時我們?nèi)绻采w了doGet方法,我們的doGet方法會被調(diào)用,請復(fù)習(xí)繼承的語法)通常我們的做法是,不覆蓋service方法,只覆蓋相應(yīng)的do方法就可以了。但有人就想覆蓋service方法, service又什么都沒干,那會發(fā)生什么?那樣的結(jié)局就是,即使你也同時覆蓋了do方法,你的do方法永遠不會被調(diào)用。我們可以看看以下的實驗,無論怎么運行,輸出的結(jié)果只有“service”,而“doGet”永遠輸出不了。
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
例:3.3.3.1
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ServletHello1 extends HttpServlet {
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
{
System.out.println("service");
}
}