您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
12-Servlet执行流程&生命周期(init、service、destroy)
发布时间:2024-11-25 22:53:01编辑:雪饮阅读()
-
servlet的声明周期中init方法是初始化方法,调用时机,默认情况下,Servlet被第一次访问时调用,调用次数为1次。
package com;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/demo01")
public class ServletTest implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("初始化方法,调用时机,默认情况下,Servlet被第一次访问时调用,调用次数为1次,例如这里访问http://localhost:8080/servlet01/demo01首次时会被调用");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello world!");
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
除此之外Servelet对象还可以修改为在服务器创建时就被调用。
package com;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(urlPatterns = "/demo01",loadOnStartup = 1)
public class ServletTest implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("初始化方法,调用时机,当loadOnStartup为非默认的-1时而是如这里的1时,则Servlet在服务器创建(运行起来后)就被创建(调用),调用次数为1次,不用访问如http://localhost:8080/servlet01/demo01也会被调用");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello world!");
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
对于service就不用多说了,会被调用多次,每次访问就调用一次。
destroy方法会在Servlet对象销毁的时候被调用,如内存释放或服务器关闭的时候。
但是服务器关闭的时候又有区分是优雅关闭时候才会,如果你在IntelliJ IDEA底部Run下面的红色方框那个停止按钮就是不会触发的,这是非优雅的关闭服务器的,相当于直接拔电源了属于是。
package com;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(urlPatterns = "/demo01",loadOnStartup = 1)
public class ServletTest implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("初始化方法,调用时机,当loadOnStartup为非默认的-1时而是如这里的1时,则Servlet在服务器创建(运行起来后)就被创建(调用),调用次数为1次,不用访问如http://localhost:8080/servlet01/demo01也会被调用");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello world!");
}
public String getServletInfo() {
return null;
}
public void destroy() {
System.out.println("销毁方法,调用时机在内存释放或服务器关闭的时候,Servlet对象会被销毁,调用次数1次");
}
}
那么你在IntelliJ IDEA中也是可以优雅的关闭,在当前项目/module选中时候打开底部的Terminal运行命令如mvn tomcat7:run
运行成功后你可以像是原本独立在tomcat中运行的startup.bat脚本中的窗口里面一样直接ctrl+c来优雅停止tomcat。只不过这里提示要你输入Y就停止,那就输入呗。
关键字词:init,service,destroy,servlet