解读 servlet

来源:互联网 发布:js正则表匹配标点符号 编辑:程序博客网 时间:2024/06/05 12:50

学习servlet,最重要的就是理解servlet下面四个点:
       1.了解Servlet API的常用接口和类

       2.掌握Servlet的生命周期

       3.掌握Servlet的部署和配置

       4.会使用Servlet处理用户请求( get, post)

用过jsp的应该知道,servlet技术是诞生在jsp之前的,servlet是一个 Java程序,是在j2ee服务器上运行以处理客户端求并做出响应的程序.

 通过查阅api可以知道,servlet和其子接口genericservlet都是很少用到的,通过文档可知它有个抽象类HttpServlet,我们每次用它的时候必须实现它,既自己写个类继承自这个HttpServlet类

在文档中对其生命周期的描述是:Servlet生命周期:
1. The servlet is constructed, then initialized with the init method.
2. Any calls from clients to the service method are handled.
3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

即先执行构造函数,然后执行init()函数,再执行servic函数,再执行doGet函数:

package com.yc.web.servlets;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LifeServlets   extends HttpServlet{public LifeServlets(){System.out.println("构造方法");}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("get方法");}@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("service方法");super.service(req, resp);}@Overridepublic void destroy() {System.out.println("destroy方法");super.destroy();}@Overridepublic void init() throws ServletException {System.out.println("init()方法");super.init();}}
配置信息:

<servlet>  <servlet-name>life</servlet-name>  <servlet-class>com.yc.web.servlets.LifeServlets</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>life</servlet-name>  <url-pattern>*.do</url-pattern>  </servlet-mapping>
执行代码:


通过在不同浏览器执行这段代码可知,servlet是通过单例模式实现的,即它只创建一个实例

  该模式同一时刻只有一个实例,不会出现信息同步与否的概念。
     若多个用户同时访问一个这种模式的页面,
     那么先访问者完全执行完该页面后,后访问者才开始执行。

所以,一旦servlet的容器关闭(这里是tomcat),就会执行destroy()方法。

 
 第一次访问:  构造 -> init()  -> service  -> doGet()/doPost()
 第二次访问:                     service ->  doGet()/doPost()
 销毁:关闭容器.   -> destroy()
      

 servlet是单实例的. 线程不安全的.


0 0
原创粉丝点击