一、Servlet接口,sun公司已经定义了两个默认实现类,GenericServlet和HttpServlet。
HttpServlet指的是能处理http请求的Servlet,在原有的Servlet接口上添加了一些http协议处理方法,比Servlet的接口功能更为强大,因此在编写Servlet的时候,通常应该继承这个类,而不是直接实现Servlet接口。
HttpServlet在实现Servlet接口的时候,覆写了service方法,该方法体内的代码互自动判断用户的请求方式,如果是get请求,就会调用HttpServlet里的doGet方法,如果是Post请求,就会调用doPost方法,因此在开发的时候,通常只需要覆写doGet方法或doPost方法,而不需要覆写service方法。
在api文档中,也已经说明了建议:
Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. **A subclass of HttpServlet must override at least one method, usually one of these:
-
- doGet, if the servlet supports HTTP GET requests
-
- doPost, for HTTP POST requests
-
- doPut, for HTTP PUT requests
-
- doDelete, for HTTP DELETE requests
-
- init and destroy, to manage resources that are held for the life of the servlet
-
- getServletInfo, which the servlet uses to provide information about itself
There’s almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).
Likewise, there’s almost no reason to override the doOptions and doTrace methods.
没必要重写那几个方法,有必要重写的只有建议的六个方法。
我们还在上一个自己写的Servlet里面来创建一个新的Servlet例子,平行于servDemo新建另一个Servlet文件。
在新建的时候我们不选择class文件而选择直接new一个Servlet,这时候里面会让我们选择要继承的父类等等信息,要重写的方法等等。
@WebServlet("/servletDemo2")
public class servletDemo2 extends HttpServlet {
private static final long serialVersionUID = 1L;
public servletDemo2() {
super();