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
目录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
initmethod 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 许可协议。转载请注明出处!
相关文章
在Linux-Ubuntu上配置开发JavaFx程序-(更新)
前言 不清楚什么原因,网络上关于JavaFx的中文资料很少,并且都很老,所以建议大家有兴趣学习JavaFx还是看官方文档比较好,而且貌似部分人不看好JavaFx。 关于Swing的资料倒是要多很多。我觉得挺奇怪的,从设计上来将,还是JavaFx高明一些嘛。 PS:经过近一周的折腾和探索,发现OpenJDK使用JavaFX真的好多坑~ OpenJDK 和 Oracle JDK的配置是有差别的,这里推
2022-05-27 · Java · 约 1 分钟
Apache-Commons-IO-最佳实践
本文列举了Java输入输出部分(IO area)的大量“最佳实践”(best practices)。 java.io.File 通常你需要去处理文件或文件名时,有许多会出错的情况: 一个类可在Unix运行但不能在Windows运行,反之亦然。 由于双路径分隔符(path separator)或缺失路径分隔符(path separator)导致文件名无效。 (在Windows上的)符合通用命名标准(
2022-05-27 · Java · 约 1 分钟
深入Jar包:Gradle构建可执行jar包与访问jar包中文件夹与文件
前言 Java的跨平台功能听起来很诱人可口,号称“Write Once,Run Everywhere”,实际上是“Run Once,Debug Everywhere”... 在实际开发过程中还是会遇到各种各样的坑的,刚刚解决了一系列问题,特地写个文章总结一下。 使用Gradle构建Jar包 感谢万能的Gradle,极大提高了Java开发的生产力~ 在Gradle中生成jar包可以使用官方的插件:a
2022-05-27 · Java · 约 1 分钟
JavaWeb开发---使用IDEA创建Servlet程序
前言 最近做项目需要,从之前熟悉的PHP和Python转到了JavaWeb,所以就有了这个笔记。资源图片都是来自网上的资源,根据自己的实际操作应用,做了总结归纳。 所需工具 JDK Tomcat IDEA 创建工程 设置工程名字: 创建完成后工程结构如下: 上面的图片是在网络上复制的,好像我用的IDEA 2017.3.2没有这个Create web.xml的选项,我也不知道为啥,难道是IDEA越更
2021-12-18 · Java · 约 1 分钟
讨论
共 0 条加载评论中…