1、通过web.xml方式
java
复制代码
5)Servlet的启动时机
- 默认情况下,servlet是不会随着容器的启动而被实例化的,只有当第一次给我发请求时才会被实例化
那么,这种情况对于第一次请求是不公平的
因此,为了提高用户体验度,提高服务器的响应速度。我们会设置Servlet的启动时机,让他随着容器的启动而被实例化
- 设置启动时机:
web.xml:<load-on-startup>从0开始的正整数</load-on-startup>
XML
复制代码
<?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_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Hello06</servlet-name>
<servlet-class>com.csdn.servlet.StartOccasionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Hello06</servlet-name>
<url-pattern>/h06</url-pattern>
</servlet-mapping>
</web-app>
java
复制代码
package com.csdn.servlet;
import jakarta.servlet.GenericServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
public class StartOccasionServlet extends GenericServlet {
public StartOccasionServlet() {
System.out.println("H06正在实例化...");
}
@Override
public void init() throws ServletException {
System.out.println("H06正在初始化...");
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("H06正在服务...");
}
@Override
public void destroy() {
System.out.println("H06正在销毁...");
}
}
H06正在实例化...
H06正在初始化...