1、配置监听,实现ServletContextListener
web.xml:
<listener>
<display-name>startThreadHelloWorld</display-name>
<listener-class>com.relive.listener.HelloListener</listener-class>
</listener>
java代码:
public class HelloListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("执行销毁方法...");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("启动监听,执行初始化方法...");
}
}
在contextInitialized(ServletContextEvent sce)方法中启动线程或任意其他服务。
2、配置servlet,继承GenericServlet类
web.xml:
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.relive.servlet.HelloServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/helloServlet/*</url-pattern>
</servlet-mapping>
java代码:
public class HelloServlet extends GenericServlet {
private static final long serialVersionUID = -566043926299855050L;
public void init(ServletConfig config) throws ServletException {
System.out.println("执行servlet..init方法..");
}
public void service(ServletRequest sRequest, ServletResponse sResponse)
throws ServletException, IOException {
System.out.println("执行servlet..service方法..");
}
}