Servlet(生命周期)
程序员文章站
2022-04-09 08:29:40
上面是web.xml 下面是servletlife java类 ......
<?xml version="1.0" encoding="utf-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<description>this is the description of my j2ee component</description>
<display-name>this is the display name of my j2ee component</display-name>
<servlet-name>servletlife</servlet-name>
<servlet-class>com.sxt.in.servletlife</servlet-class>
<load-on-startup>1</load-on-startup><!-- 加载服务器启动流 -->
</servlet>
<servlet-mapping>
<servlet-name>servletlife</servlet-name>
<url-pattern>/life</url-pattern>
</servlet-mapping>
</web-app>
上面是web.xml
下面是servletlife java类
package com.sxt.in;
import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
/**
* servlet生命周期
* 1从第一次被调用到服务器结束
* 2如果servlet在xml中配置了load-on-startup生命周期为, 从服务器启动到服务器关闭
* 注意:
* init方法是对servlet进行初始化的一个方法会在servlet第一次进行存储时执行
* destory方法是servlet被销毁时执行,也就是服务器关闭的时候
*
* @author administrator
*
*/
public class servletlife extends httpservlet {
@override//初始化方法在servlet第一次加载内容时被调用
public void init() throws servletexception {
system.out.println("servlet 初始化完成");
}
@override//service方法是真正处理请求的方法
protected void service(httpservletrequest req, httpservletresponse resp)
throws servletexception, ioexception {
resp.getwriter().write("servlet life");//servlet只要服务器在他就在
system.out.println("servlet life");
}
@override
public void destroy() {
system.out.println("我被销毁了");
}
}
上一篇: PHP Mysql编程之高级技巧