先看类吧:(懂了就不用往下看了)
package httpListener;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class HttpSessionAttribute implements HttpSessionAttributeListener {
private Map map;
public HttpSessionAttribute(){
map = new HashMap();
}
public void attributeAdded(HttpSessionBindingEvent e) {
String userName = e.getSession().getAttribute("user").toString();
map.put(userName, userName);
e.getSession().setAttribute("map", map);
System.out.println("add...");
System.out.println(userName);
}
public void attributeRemoved(HttpSessionBindingEvent e) {
String u = e.getSession().getAttribute("u").toString();
map.remove(u);
e.getSession().setAttribute("map", map);
System.out.println("remove...");
System.out.println(u);
}
public void attributeReplaced(HttpSessionBindingEvent e) {
// TODO Auto-generated method stub
}
}
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.HttpSessionAttribute</listener-class>
</listener>
</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")){
String u = session.getAttribute("user").toString();
session.setAttribute("u",u);
session.removeAttribute("user");
}
%>
httpSessionListenerHandler.jsp
<%
String userName = request.getParameter("userName");
if(userName.trim().length() != 0){
session.setAttribute("user",userName);
}
%>
${map }<br>
<a href="httpSessionListener.jsp?action=exit">Exit</a>
知道了吧!