Servlet 类必须继承 HttpServlet,而HttpServlet继承了GenericServlet,GenericServlet 实现了 Servlet 接口。
J2EE API 中
GenericServlet :Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.
Servlet 接口有init (),destroy() ,service(ServletRequest req, ServletResponse res) 等接口,新建Servlet类由于继承了HttpServlet自然也有这些方法。
查看HttpServlet 源代码:
service 方法:
public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
该service方法最后再调用 自身的service方法。参数为:
protected void service(HttpServletRequest req, HttpServletResponse resp)
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
... 此处判断doGet(req, resp); 或者 doPost(req, resp);
再看doPost方法:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
此方法和doGet一样 方法内部只有错误信息提示,所以在编写自己的Servlet时 只需重写doPost 和 doGet 即可不用,没有必要重写service。如果不重写这这两个方法,就会出现HttpServlet里这两个方法的错误提示。