HttpServlet

(一)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()要注释掉)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值