Servlet监听器对Session监听的方法如下:
1.HttpSessionListener
public void sessionCreated(HttpSessionEvent se):创建
public void sessionDestroyed(HttpSessionEvent se):销毁
2.HttpSessionAttributeListener
public void attributeAdded(HttpSessionBindingEvent se):增加属性
public void attributeRemoved(HttpSessionBindingEvent se):删除属性
public void attributeReplaced(HttpSessionBindingEvent se):更改属性
实例:
SessionListenerLife.java:
01.
package
mgc.listener.test;
02.
03.
import
javax.servlet.http.*;
04.
05.
public
class
SessionListenerLife
implements
HttpSessionListener,HttpSessionAttributeListener {
06.
07.
private
HttpSession session =
null
;
08.
09.
public
void
sessionCreated(HttpSessionEvent se) {
10.
11.
this
.session = se.getSession();
12.
System.out.println(
"** 创建..."
) ;
13.
System.out.println(
"SessionID:"
+
this
.session.getId()) ;
14.
}
15.
16.
public
void
sessionDestroyed(HttpSessionEvent se) {
17.
18.
System.out.println(
"**销毁..."
) ;
19.
}
20.
21.
public
void
attributeAdded(HttpSessionBindingEvent se) {
22.
23.
System.out.println(
"**增加属性:"
+ se.getName() +
"-->"
+ se.getValue()) ;
24.
}
25.
26.
public
void
attributeRemoved(HttpSessionBindingEvent se) {
27.
28.
System.out.println(
"**删除属性:"
+ se.getName() +
"-->"
+ se.getValue()) ;
29.
}
30.
31.
public
void
attributeReplaced(HttpSessionBindingEvent se) {
32.
33.
System.out.println(
"**更改属性:"
+ se.getName() +
"-->"
+ se.getValue()) ;
34.
}
35.
}
web.xml:
1.
<
listener
>
2.
<
listener-class
>mgc.listener.test.SessionListenerLife</
listener-class
>
3.
</
listener
>
4.
<
session-config
>
5.
<
session-timeout
>1</
session-timeout
>
6.
</
session-config
>
sessionlistener.jsp:
01.
<%@ page contentType="text/html;charset=GB2312" %>
02.
<
html
>
03.
<
head
>
04.
<
title
>sessionlistener</
title
>
05.
</
head
>
06.
07.
<
body
>
08.
<%
09.
//设置属性
10.
session.setAttribute("mgc","Magci") ;
11.
//删除属性
12.
//session.removeAttribute("mgc") ;
13.
//销毁
14.
//session.invalidate() ;
15.
%>
16.
</
body
>
17.
</
html
>