曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
Java

Java Web Development --- Servlet Lifecycle Experiment

Preface A Servlet is a program that runs on the server side, and its running state is maintained by the Servlet container (referred to as the container). Usually, when the container receives a client request for a Servlet, the container determines whether this Servlet is being accessed for the first time. If it is the first access, it will create a Servlet instance and at the same time call that instance's init() method to initialize it. Each Servlet will only have one instance created, and it will also only be initialized once. Then this instance is kept in memory throughout to carry out on all requests

曦远 (DealiAxy)约 22 分钟
目录9 个章节

Preface

A Servlet is a program that runs on the server side, and its running state is maintained by the Servlet container (referred to as the container).

Usually, when the container receives a client request for a Servlet, the container determines whether this Servlet is being accessed for the first time. If it is the first access, it will create a Servlet instance and at the same time call that instance's init() method to initialize it.

Each Servlet will only have one instance created, and it will also only be initialized once. Then this instance is kept in memory throughout to handle all requests. The default service function is to call the do function corresponding to the HTTP request method. At the same time, the HttpServlet.service() method checks whether the request method has called the appropriate handling method.

Finally, when the server shuts down, the container will call the Servlet's destroy() method to clear the Servlet instance.

Below we will look at this process through an experiment:

Write a test JSP

First, we write a very simple JSP program, and we call the Servlet method through the JSP page. Under the webapps folder in the Tomcat installation directory, we create a new ServletLife folder, enter that folder, and write an index.jsp file. The code is as follows:

index.jsp

<%@ page contentType="text/html;charset=GBK" language="java" %>
<html>
  <head>
    <title>Show servlet life cycle</title>
  </head>
  <body>
    <center>
      <form action="ShowLifeCycle" name=form">
        <input type="submit" value="SUBMIT"></form>
    </center>
  </body>
</html>

This is a very simple JSP program, only to illustrate the point. The entire program has only one form-submitting submit.

  • Line 8 of the code specifies that the form is submitted to ShowLifeCycle
  • Line 9 of the code creates a "Submit"

Then we create a new WEB-INF folder under the /ServletLife directory we created, enter the WEB-INF folder, and then create a classes folder.

Write the Servlet program

Servlet.java code

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class Servlet extends HttpServlet {
    private ServletConfig config;
    private static int counter = 0;

    public Servlet() {
        super();
        System.out.println("=== " + ++counter + " instances ===");
    }

    //初始化servlet
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.config = config;
        System.out.println("=== invoke init() ===" + new Date().toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=== invoke doPost ===" + new Date().toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=== invoke doGet() ===" + new Date().toString());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("=== invoke service ===");
    }

    @Override
    public void destroy() {
        System.out.println("=== invoke destroy() ===" + new Date().toString());
    }
}

Code explanation

  • Line 11, define a class variable to record how many instances have been created in total.
  • Lines 13–16, explicitly write out the constructor in order to print how many instances have been created in total.
  • Lines 18–24, the initialization function. Each call displays "=== invoke init() ===" along with the current time.
  • Lines 26–28, print "=== invoke doPost ===" along with the current time in the doPost() method.
  • Lines 30–32, print "=== invoke doGet ===" along with the current time in the doGet() method.
  • Lines 34–38, here we override the service() method, only so that when this method is called it prints "””’ invoke service ===" along with the current time.
  • Lines 40–43, when the destroy() method is called, print "=== invoke destroy() ===" along with the current time.

Place the Servlet.class compiled from this java file into the /WEB-INF/classes folder.

Write the web.xml configuration

Then create a configuration file web.xml under the /WEB-INF folder:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
            <servlet-name>LifeCycle</servlet-name>
            <servlet-class>Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LifeCycle</servlet-name>
        <url-pattern>/ShowLifeCycle</url-pattern>
    </servlet-mapping>
</web-app>

This file is mainly used to configure the Servlet.

Run Tomcat

Next, run Tomcat and check the console log. There will be a line of text that was just printed:

13-Jan-2018 10:26:21.214 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 108 ms

This indicates that the Tomcat server started normally.

Then we enter the following URL in the browser address bar:

http://localhost:8080/ServletOne/

There is only a submit button on the page

Analyze the log test

Click this button. At this point the Servlet is requested. Check the console output, which is now as follows:

=== 1 instances ===
=== invoke init() ===Sat Jan 13 10:26:30 CST 2018
=== invoke doGet() ===Sat Jan 13 10:26:30 CST 2018
=== invoke service ===
  • Line 2, when this Servlet request is received for the first time, it will call this Servlet's instance method and create 1 instance. "=== 1 instances ===";
    • Line 3, after creating the instance, call the Servlet's init() method to perform initialization;
  • Line 4, handle the request and response through the doGet() method;
  • Line 5, print "=== invoke service ===" on the last line of the service() method. In fact, the doGet() method is called by the service() method.

Next we create a Servlet request again, open the browser, repeat the above process, find the localhost/8080/ServletLife/index.jsp page, click submit, then reopen the text document from just now. The content is as follows:

=== 1 instances ===
=== invoke init() ===Sat Jan 13 10:26:30 CST 2018
=== invoke doGet() ===Sat Jan 13 10:26:30 CST 2018
=== invoke service ===
13-Jan-2018 10:26:31.202 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\manager]
13-Jan-2018 10:26:31.272 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\manager] has finished in [70] ms
=== invoke doGet() ===Sat Jan 13 10:33:10 CST 2018
=== invoke service ===

Two new lines, 6 and 7, have been added. Requesting the Servlet again does not create a new Servlet instance, nor is there an init process; it directly uses the instance created last time to handle the request and response, and the doGet() method is called.

Then we shut down the Tomcat server. Check the console log, the content is as follows:

=== 1 instances ===
=== invoke init() ===Sat Jan 13 10:26:30 CST 2018
=== invoke doGet() ===Sat Jan 13 10:26:30 CST 2018
=== invoke service ===
13-Jan-2018 10:26:31.202 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\manager]
13-Jan-2018 10:26:31.272 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\manager] has finished in [70] ms
=== invoke doGet() ===Sat Jan 13 10:33:10 CST 2018
=== invoke service ===
=== invoke destroy() ===Sat Jan 13 10:33:20 CST 2018

You can see that the destroy() method is called, clearing the Servlet instance.

Summary

Servlet lifecycle

  • The browser submits a request to the Servlet, the Servlet is instantiated
  • The Servlet executes the init method and continuously responds to HTTP requests
  • The browser/page is closed, the Servlet instance is destructed

_EOF_

Java Web Development --- Servlet Lifecycle Experiment

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

2020年第一次用上Struts2框架做Web开发的体验

SliiyStruts2 又名 sb-struts2,因为struts真的太难用了(也许在很多年前是很好用的,但是现在看来,被其他框架秒成渣) 前言 想不到我还是得和这struts框架打交道啊,从一开始学web的时候就十分抵制这类古老,使用反人类的框架,不过为了帮女朋友做个学校的作业,还是得搞一下,然而,半小时就写好的业务代码,因为我不熟悉这个框架和Java的这套体系,调试了半天才成功run起来…

2022-06-17 · Java · 约 1 分钟

在Linux-Ubuntu上配置开发JavaFx程序-(更新)

前言 不清楚什么原因,网络上关于JavaFx的中文资料很少,并且都很老,所以建议大家有兴趣学习JavaFx还是看官方文档比较好,而且貌似部分人不看好JavaFx。 关于Swing的资料倒是要多很多。我觉得挺奇怪的,从设计上来将,还是JavaFx高明一些嘛。 PS:经过近一周的折腾和探索,发现OpenJDK使用JavaFX真的好多坑~ OpenJDK 和 Oracle JDK的配置是有差别的,这里推

2022-05-27 · Java · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…