servlet简介

   web 开发分为两种:静态开发(使用html)和动态开发(使用servlet/jsp,jsp就是servlet,ASP ,PHP)

   所以servlet是sun公司提供的一门专门用于开发动态web资源的技术

    sun公司在API中提供一个servlet接口,用户如果想开发一个动态web资源,需要完成二步

     1. 编写一个Java类,实现servlet接口

     2. 把开发好的Java类部署到web服务器

   sun公司已经实现了servlet的两个默认实现类,所以我们在使用它的时候只需要继承这两个类就行了

  A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. 

  To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet. 

  This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods (生命周期相关的方法)and are called in the following sequence: 

  The servlet is constructed, then initialized with the init method.

  Any calls from clients to the service method are handled.

  The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

  In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.

  生命周期相关的方法:(比如人这个对象20岁上大学,25岁找工作)生命中某个特点时期必定要执行的方法。

Servlet生命周期:

  浏览器向服务器发送请求

  第一次创建servlet实例对象

  调用servlet的init方法完成对象的初始化

  创建代表请求的request和代表相应的response对象,然后调用servlet的service方法相应客户端请求

  Service方法执行,向代表客户机响应的response对象写入向客户机输出的数据

  Service方法返回,此时response里面有数据

  服务器从response里取出数据,构出一个http响应回写给客户机

  Servlet对象创建后会驻留在服务器中,为所有用户服务

  当关掉web服务器后会消失

  并调用destroy()

  客户的每次请求都会在服务器中创建一个response和request对象,但是这两个对象的生命周期很短,请求结束,对象即销毁

    所以,默认的servlet对象是在用户请求的时候才创建,并不是在启动服务器的时候创建,但是如果加上一个标签:

	<servlet>
	   <servlet-name>ServelDemol</servlet-name>
	   <servlet-class>cn.itcast.ServelDemol</servlet-class>
	   <load-on-startup>2</load-on-startup>
	</servlet>

  就会在启动服务器的时候就创建servlet对象

学好servlet的关键就是知道在创建servlet对象的同时,也同时创建了哪些相关对象,有以下几个:

Request

Response

ServletConfig

ServletContext

Session

Cookie

原文地址:https://www.cnblogs.com/tech-bird/p/3804103.html