(一)HttpServlet是什么
Servlet 是一个接口,而GenericServlet 实现了Servlet 接口,是通用的Servlet,而HttpServlet 继承了GenericServlet .
HttpServlet 是基于HTTP协议的Servlet,我们一般都是使用HttpServlet的。
(二)使用HttpServlet 一般只需注重4个方法:doGet() doPost() 和 init() ,init(ServletConfig config)
(1)doGet():
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
当浏览器使用GET方法向tomcat服务器发送请求时,自动就会调用 doGet()
(2)doPost():
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
当浏览器使用POST方法向tomcat服务器发送请求时,自动就会调用doPost()
(3)init():
public void init() throws ServletException {}
当HttpServlet对象被创建时,自动调用init(),用于初始化.
(4)init(ServletConfig config)
ServletConfig config 是用于获取web.xml中的变量的
(三)示例代码:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpServlet_demo extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
System.out.println("doGet was called");
resp.getOutputStream().write("hello HttpServlet".getBytes());
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doPost(req, resp);
}
public void init() throws ServletException {
super.init();
System.out.println("HttpServlet was created");
}
}
当浏览器使用 GET方法发送请求时,控制台会显示doGet was called,浏览器会显示 hello HttpServlet
(注意:当用IDE自动生成方法时,doGet()和doPost()的super.doGet()或super.doPost()要注释掉)