类的写法如下:
package httpListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class HttpSession implements HttpSessionListener {
private int counter;
public HttpSession(){
counter = 0;
}
public void sessionCreated(HttpSessionEvent e) {
counter++;
e.getSession().setAttribute("counter", counter);
System.out.println(counter+"+++++++++++++++++++++++++++++++++");
}
public void sessionDestroyed(HttpSessionEvent e) {
counter--;
e.getSession().setAttribute("counter", counter);
System.out.println(counter+"=================================");
}
}
web.xml中这样配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>httpListener.HttpSession</listener-class>
</listener>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
同样用两个页面说明其用法:
httpSessionListener.jsp
<form action="httpSessionListenerHandler.jsp" method="get">
<input type="text" name="userName">
<input type="submit" value="send">
</form>
<%
String action = request.getParameter("action");
if(action == null){
action = "";
}
if(action.equals("exit")){
session.removeAttribute("user");
}
%>
httpSessionListenerHandler.jsp
<%
String userName = request.getParameter("userName");
if(userName.trim().length() != 0){
session.setAttribute("user",userName);
}
%>
${counter }<br>
<a href="httpSessionListener.jsp?action=exit">Exit</a>
没了,就是这么简单,没有什么照虎画猫就行了,小薛老师说过,
你照着做一遍不行,就两遍,十遍之后不会再来问我。
我很笨,所以我照着一遍就会了...