1、Java Web中没有像asp.net的全局启动事件,但是可以通过web.xml中的load-on-startup节点来控制Servlet的开机启动和启动次数。web.xml详细配置参考:http://www.cnblogs.com/EasonJim/p/6221952.html
灵感出自:
http://*.com/questions/4122437/java-equivalent-to-asp-net-global-asax
http://*.com/questions/16535998/session-start-event-handler-in-jsp
配置如下:
<!-- 配置类似asp.net的Global.asax -->
<servlet>
<display-name>ProcessServlet</display-name>
<servlet-name>ProcessServlet</servlet-name>
<servlet-class>com.jsoft.jblog.servlet.ProcessServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
Servlet:
package com.jsoft.jblog.servlet; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; public class ProcessServlet extends HttpServlet { public void init() throws ServletException
{
System.out.println("[info] Global Start Up");
} public void destroy() {
System.out.println("[info] Global End");
}
}
上面已经实现了Global的启动和结束事件,那么Session的启动和结束实现应该如何去实现?
web.xml配置:
<!-- 配置SessionStart -->
<listener>
<listener-class>com.jsoft.jblog.servlet.SessionListener</listener-class>
</listener>
Servlet:
package com.jsoft.jblog.servlet; import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; public class SessionListener implements HttpSessionListener { @Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
System.out.println("[info]SessionCreated");
} @Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("[info]SessionDestroyed");
}
}