Sevrlet 生命周期
发布日期:2021-06-30 14:57:01 浏览次数:3 分类:技术文章

本文共 2521 字,大约阅读时间需要 8 分钟。

package com.jerry.servlet;import java.io.IOException;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet(asyncSupported = true, urlPatterns = {
"/lifecycle" })public class Lifecycle extends HttpServlet {
private static final long serialVersionUID = 1L; // servlet是单例模式,所以只会构造一次 public Lifecycle() {
super(); System.out.println("构造函数:Lifecycle()"); } // 初始化当然也只会执行一次 public void init(ServletConfig config) throws ServletException {
System.out.println("初始化函数:init(ServletConfig config)"); } // 每次访问就是调用 service 啦。service 判断请求类型再去调度 doGet 或 doPost protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("调用:service"); // doGet、doPost其实是由service调用的。如果我们重写了 service,又没手动调用他们,那么doGet、doPost就成失踪人口了。 super.service(request, response);// 如果没有什么特殊需求,直接调用父类的 service 就行了。 } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("调用:doGet"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response); System.out.println("调用:doPost"); } // servlet实例被销毁前调用一次,交代后事。(要正常关闭 tomcat 如果直接关 tomcat 那遗言的机会都没有了) public void destroy() {
System.out.println("析构函数:destroy()"); }}

访问:

输出如下

构造函数:Lifecycle() 初始化函数:init(ServletConfig config)调用:service调用:doGet

随便编辑下 Lifecycle.java 触发Eclipse 的 **“自动重建”**观察 sevrlet 的销毁过程。

十一月 16, 2018 10:54:12 下午 org.apache.catalina.core.StandardContext reload信息: Reloading Context with name [/servlet_demo] has started析构函数:destroy()十一月 16, 2018 10:54:12 下午 org.apache.catalina.core.StandardContext reload信息: Reloading Context with name [/servlet_demo] is completed

至于tomcat是怎么根据我们输入的URL找到具体 servlet的呢?

1、从URL 中提取出路径 lifecycle

2、到 servlet-mapping 》 url-pattern 匹配
3、配上了就用它的 servlet-name 找 servlet-name 相同 servlet 节点
4、得到了类名 com.jerry.servlet.Lifecycle 就可以用反射为所欲为了

...
Lifecycle
com.jerry.servlet.Lifecycle
Lifecycle
/lifecycle
...

servlet 默认都是懒加载,有访问时才实例化。如果一些servlet需要服务器启动就实例化可以加上 load-on-startup 数字越小优先级越高

Lifecycle
com.jerry.servlet.Lifecycle
1

转载地址:https://jerryjin.blog.csdn.net/article/details/84147008 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Attribute “resulMap“ must be declared for element type “select“
下一篇:手动打包 Jar

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月08日 00时57分22秒