深入理解servlet之servlet模拟请求get和post和servlet生命周期

模拟Get请求和Post请求的分发

1)修改代码如下:

@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
			//System.out.println("我的第一个手写servlet");
		//servletrequest对象强制转换为httpservletrequest对象
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		// get请求获取到"GET" ,post请求获取到"POST"字符串
		String method = httpServletRequest.getMethod();
		System.out.println("请求的方法为:"+method);
		if("GET".equals(method)) {// 根据请求的方式 执行不同的方法去做不同的处理
			doGet();
		}else if("POST".equals(method)) {// 根据请求的方式 执行不同的方法去做不同的处理
			doPost();
		}
		
	}
	private void doPost() {
		System.out.println("POST请求处理方法");
		
	}
	private void doGet() {
		System.out.println("GET请求处理方法");
		
	}

2)准备html页面表单内容如下(分别测试get请求和post请求):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Insert title here</title>
	</head>
	
	<body>

		<form action="http://localhost:8080/servletFirst/hello" method="post">
			用户名:<input name="username" type="text" /><br />
			密码:<input name="password" type="password" /><br />
			<input type="submit" />
		</form>

	</body>
</html>

测试get请求的打印如下:

测试post请求的打印如下:

Servlet生命周期

servlet的生命周期。

什么时候创建一个servlet?

什么时候去销毁一个servlet?

Servlet的生命周期

1.先调用 Servlet的构造方法

2.调用 init 方法 初始化Servlet

3.调用 Servlet中的service方法处理请求操作

4.调用 destory方法 执行Servlet销毁的操作

init方法:当服务器创建一个serlvet的时候,会去调用init方法。

         当我们第一次去访问一个servlet的时候,会去创建这个servlet对象。并且只会创建一次。

当我们继承HttpServlet类实现Servlet程序,重写init(Servletconfig config) 方法的时候,一定要在里面写上。super.init(config);

否则后面调用getServletContext()方法就会报空指针异常

 

   @Override

   publicvoidinit(ServletConfig config) throwsServletException {

      super.init(config); // 一定要写上,因为在父类的方法中。这里保存了ServletConfig的引用

     

   }

 

   @Override

   protectedvoid doGet(HttpServletRequestreq, HttpServletResponse resp) throwsServletException,

         IOException {

      getServletContext(); // 如果没有super.init(config)调用。这里就会报空指针异常

   }

 


  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值