ServletListener 之 监听HTTP会话

本文介绍如何使用Java Servlet技术实现HTTP会话监听及请求监听功能,包括监听会话的创建与销毁、监听会话中对象的绑定信息等。同时提供了一套完整的示例代码,涵盖会话管理、显示、注销等多个环节。

在开始先要知道我们可以通过HttpSessionListener接口监听HTTP会话的创建,销毁的信息;通过HTTPSessionActivationListener监听HTTP会话的active,passivate情况;通过HttpSessionBindingListener监听HTTP会话中对象的绑定信息;通过HttpSessionAttributeListener监听HTTP会话中属性的设置情况 。
下面写个具体的例子:

ContractedBlock.gif ExpandedBlockStart.gif 监听HTTP会话程序
None.gifpackage eflylab;
None.gif
import java.util.Hashtable;
None.gif
import java.util.Iterator;
None.gif
import javax.servlet.http.HttpSession;
None.gif
import javax.servlet.http.HttpSessionEvent;
None.gif
import javax.servlet.http.HttpSessionListener;
None.gif
None.gif
//HttpSessionListener接口监听会话的创建,销毁的信息
ExpandedBlockStart.gifContractedBlock.gif
public class SessionListener implements HttpSessionListener dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 该类实现了HttpSessionListener接口。
InBlock.gif     * 该类还有一个属性Hashtable,用来保存所有的登录信息。
InBlock.gif     * 当创建一个Session时,就调用 sessionCreate()方法将登录会话保存到Hashtable中;
InBlock.gif     * 当销毁一个Session时, 就调用sessionDetoryed()方法将 登录信息从Hashtable中移除
InBlock.gif     * 这就就实现了管理在线用户登录的会话信息目的 
ExpandedSubBlockEnd.gif     
*/

InBlock.gif    
// 集合对象,保存session 对象的引用
InBlock.gif
    static Hashtable ht = new Hashtable();
InBlock.gif
InBlock.gif    
// 实现HttpSessionListener接口,完成session创建事件控制
ExpandedSubBlockStart.gifContractedSubBlock.gif
    public void sessionCreated(HttpSessionEvent arg0) dot.gif{
InBlock.gif        HttpSession session 
= arg0.getSession();
InBlock.gif        ht.put(session.getId(), session);
InBlock.gif        System.out.println(
"create session :" + session.getId());
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
// 实现HttpSessionListener接口,完成session销毁事件控制
ExpandedSubBlockStart.gifContractedSubBlock.gif
    public void sessionDestroyed(HttpSessionEvent arg0) dot.gif{
InBlock.gif
InBlock.gif        HttpSession session 
= arg0.getSession();
InBlock.gif        System.out.println(
"destory session :" + session.getId());
InBlock.gif        ht.remove(session.getId());
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
// 返回全部session对象集合
ExpandedSubBlockStart.gifContractedSubBlock.gif
    static public Iterator getSet() dot.gif{
InBlock.gif        
return ht.values().iterator();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
// 依据session id返回指定的session对象
ExpandedSubBlockStart.gifContractedSubBlock.gif
    static public HttpSession getSession(String sessionId) dot.gif{
InBlock.gif        
return (HttpSession) ht.get(sessionId);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
ExpandedBlockEnd.gif}

None.gif

 

ContractedBlock.gif ExpandedBlockStart.gif 测试会话监听的程序index.jsp
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ page contentType="text/html; charset=gb2312" %> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif 
InBlock.gif        
String strName = null;
InBlock.gif        
String strThing = null;
InBlock.gif        try {
InBlock.gif            strName 
= request.getParameter("name");
InBlock.gif            strThing 
= request.getParameter("thing");
InBlock.gif            
if ((strName == null) || (strName.length() == 0)) {
InBlock.gif                throw 
new Exception("null strName");
InBlock.gif            }
InBlock.gif            
if ((strThing == null) || (strThing.length() == 0))
InBlock.gif                throw 
new Exception("null strThing");
InBlock.gif            session.setAttribute(
"name", strName);
InBlock.gif            session.setAttribute(
"thing", strThing);
InBlock.gif            response.sendRedirect(
"display.jsp");
InBlock.gif        } catch (Exception e) {
ExpandedBlockEnd.gif        } 
None.gif
%> 
None.gif
<html> 
None.gif
<head> 
None.gif
<title>会话管理</title> 
None.gif
</head> 
None.gif
<body> 
None.gif
<center>会话管理示例</center> 
None.gif
<form action="" method="post" >
None.gif    
<table align=''center''> 
None.gif        
<tr> 
None.gif            
<td>名称:</td> 
None.gif              
<td> <input name="name" type="input"/> </td> 
None.gif        
</tr> 
None.gif        
<tr> 
None.gif            
<td>事件:</td> 
None.gif            
<td> <input name="thing" type="input"/> </td> 
None.gif        
</tr> 
None.gif        
<tr> 
None.gif            
<td align=''right''> </td> 
None.gif            
<td align=''right''> 
None.gif                
<button type="submit">提交</button> 
None.gif                
<button type="reset">重置</button> 
None.gif            
</td> 
None.gif        
</tr> 
None.gif    
</table> 
None.gif
</form> 
None.gif
</body> 
None.gif
</html> 
None.gif

当访问上面页面时就会出现一个登录框,输入后进入display.jsp显示刚才输入的内容

ContractedBlock.gif ExpandedBlockStart.gif 会话信息显示的程序 display.jsp
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ page language="java" pageEncoding="GB2312" %> 
None.gif
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> 
None.gif
<html> 
None.gif
<head> 
None.gif
<title>会话控制显示</title> 
None.gif
</head> 
None.gif
<body bgcolor="#FFFFFF"> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif 
InBlock.gif
if (session.isNew()==true){ 
InBlock.gif    response.sendRedirect(
"index.jsp"); 
InBlock.gif
InBlock.gifout.println(
"name: "+ session.getAttribute("name"+ "<br>"); 
InBlock.gifout.println(
"thing: "+ session.getAttribute("thing"+ "<br>"); 
InBlock.gifout.println(
"session id: " + session.getId() + "<br>"); 
ExpandedBlockEnd.gifout.println(
"create time: " + session.getCreationTime() ); 
None.gif
%> 
None.gif
<form >
None.gif  
<table>
None.gif      
<tr>
None.gif        
<td><href="session.jsp">管理</a></td>&nbsp;&nbsp;&nbsp;&nbsp;
None.gif        
<td><href="logout.jsp">注销</a></td>&nbsp;&nbsp;&nbsp;&nbsp;
None.gif    
</tr>
None.gif  
</table>
None.gif
</form>
None.gif
</body> 
None.gif
</html> 
None.gif

单击管理即进入管理页面session.jsp,单击注销就会进入 会话注销页面 logout.jsp使 HTTP会话无效

ContractedBlock.gif ExpandedBlockStart.gif 会话管理程序 session.jsp
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ page language="java" pageEncoding="GB2312" %> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif@ page import= "eflylab.*,java.util.*"%> 
None.gif
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> 
None.gif
<html> 
None.gif
<head> 
None.gif
<title>Lomboz JSP</title> 
None.gif
</head> 
None.gif
<body bgcolor="#FFFFFF"> 
None.gif会话管理
None.gif
<br> 
None.gif
<table border=''1''> 
None.gif
<tr bgcolor=''yellow''> 
None.gif
<td>会话 id</td> 
None.gif
<td>用户名 </td> 
None.gif
<td>事件</td> 
None.gif
<td>创建时间 </td> 
None.gif
<td>操作</td> 
None.gif
</tr> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif 
InBlock.gifIterator iterator 
= SessionListener.getSet(); //获得返回全部session对象集合
InBlock.gif
while(iterator.hasNext()){ 
InBlock.gif    try{ 
InBlock.gif        HttpSession session1 
= (HttpSession)iterator.next(); 
InBlock.gif        out.println(
"<tr>"); 
InBlock.gif        out.println(
"<td>" + session1.getId() + "</td>" ); 
InBlock.gif        out.println(
"<td>" + session1.getAttribute("name"+ "</td>" ); 
InBlock.gif        out.println(
"<td>" + session1.getAttribute("thing"+ "</td>" ); 
InBlock.gif        out.println(
"<td>" + session1.getCreationTime() + "</td>" ); 
ExpandedBlockEnd.gif        
%>
None.gif        
<td> <href='end.jsp?sessionid=<%=session1.getId() %>'>销毁</a> </td> 
ExpandedBlockStart.gifContractedBlock.gif        
<%dot.gif
InBlock.gif        out.println(
"</tr>"); 
InBlock.gif        System.out.println(
"sessionId " + session1.getId()); 
InBlock.gif    }catch(Exception ex){ 
InBlock.gif        ex.printStackTrace(); 
InBlock.gif        return; 
InBlock.gif    } 
ExpandedBlockEnd.gif
None.gif
%> 
None.gif
</table> 
None.gif
</body> 
None.gif
</html> 
None.gif

 

ContractedBlock.gif ExpandedBlockStart.gif 注销会话的程序 logout.jsp
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ page language="java" pageEncoding="GB2312" %> 
None.gif
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> 
None.gif
<html> 
None.gif
<head> 
None.gif
<title>会话控制</title> 
None.gif
</head> 
None.gif
<body bgcolor="#FFFFFF"> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif 
InBlock.gif
if(session.isNew()!=true){ 
InBlock.gif    session.invalidate(); 
InBlock.gif
ExpandedBlockEnd.gifresponse.sendRedirect(
"index.jsp"); 
None.gif
%> 
None.gif
</body> 
None.gif
</html> 
None.gif

 

ContractedBlock.gif ExpandedBlockStart.gif 强制移除会话的程序 end.jsp
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ page language="java" pageEncoding="GB2312" %> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif@ page import="eflylab.*"%> 
None.gif
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> 
None.gif
<html> 
None.gif
<head> 
None.gif
<title>Lomboz JSP</title> 
None.gif
</head> 
None.gif
<body bgcolor="#FFFFFF"> 
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif 
InBlock.gif
// 关闭会话,释放资源
InBlock.giftry { 
InBlock.gif    
String strSid = request.getParameter("sessionid"); 
InBlock.gif    HttpSession session1 
= SessionListener.getSession(strSid); //根据ID获取 Session
InBlock.gif    
if (session1!=null){ 
InBlock.gif        session1.invalidate(); 
InBlock.gif    } 
InBlock.gif} catch (Exception e) { 
InBlock.gif    e.printStackTrace(); 
InBlock.gif
ExpandedBlockEnd.gifresponse.sendRedirect(
"session.jsp"); 
None.gif
%> 
None.gif
</body> 
None.gif
</html> 
None.gif

 

ContractedBlock.gif ExpandedBlockStart.gif 部署文件 web.xml
None.gif<?xml version="1.0" encoding="UTF-8"?>
None.gif
<web-app version="2.4" 
None.gif    xmlns
="http://java.sun.com/xml/ns/j2ee" 
None.gif    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" 
None.gif    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee 
None.gif    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
None.gif
None.gif
<listener>
None.gif    
<listener-class>eflylab.SessionListener</listener-class>
None.gif
</listener>
None.gif
</web-app>
None.gif


 

对请求的监听
在Servlet2.4规范中,新加了一个技术,就是可以监听客户端的请求。一旦能够在监听程序中获取客户端的请求,就可以对请求进行统一处理。比如做一个WEB管理程序,如果在梧桐访问,就可以不登录,如果是远程访问,那么就需要登录。这样我们就可以 监听客户端的请求,从请求中获得客户端地址,并通过这个地址做出对应的处理。
我们在上面例子的基础上再扩展一下!

None.gif package  eflylab;
None.gif
None.gif
import  javax.servlet. * ;
None.gif
None.gif
public   class  MyRequestListener 
None.gif
implements  ServletRequestListener,ServletRequestAttributeListener
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
//ServletRequestListener
InBlock.gif
    public void requestDestroyed(ServletRequestEvent sre) 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        logout(
"request destroyed");
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
public void requestInitialized(ServletRequestEvent sre) 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
//在这个方法里,获得客户端请求对象,然后通过这个请求对象获得访问
InBlock.gif        
//的客户端IP地址。如果该地址是“127”开的,那么就认为它是从本机访问
InBlock.gif        
//就在请求中设置一个isLogin的属性,并且这个属性的值为Boolean(true)
InBlock.gif        
//对象,如果不是从本机访问,那么就必须把这个属性设置成Boolean(false)对象
InBlock.gif
        
InBlock.gif        logout(
"request init");//日志
InBlock.gif
        ServletRequest sr=sre.getServletRequest();
InBlock.gif          
InBlock.gif        
if(sr.getRemoteAddr().startsWith("127"))
InBlock.gif            sr.setAttribute(
"isLogin",new Boolean(true));
InBlock.gif        
else 
InBlock.gif            sr.setAttribute(
"isLogin",new Boolean(false));
InBlock.gif        
InBlock.gif        
ExpandedSubBlockEnd.gif    }
//ServletRequestListener
InBlock.gif    
InBlock.gif    
//ServletRequestAttributeListener
InBlock.gif
    public void attributeAdded(ServletRequestAttributeEvent event) 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        logout(
"attributeAdded('" + event.getName() + "', '" +
InBlock.gif        event.getValue() 
+ "')");
ExpandedSubBlockEnd.gif    }

InBlock.gif    
public void attributeRemoved(ServletRequestAttributeEvent event) 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        logout(
"attributeRemoved('" + event.getName() + "', '" +
InBlock.gif        event.getValue() 
+ "')");
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
public void attributeReplaced(ServletRequestAttributeEvent event)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        logout(
"attributeReplaced('" + event.getName() + "', '" +
InBlock.gif        event.getValue() 
+ "')");
InBlock.gif        
ExpandedSubBlockEnd.gif    }
//ServletRequestAttributeListener
InBlock.gif
    private void logout(String msg)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        java.io.PrintWriter out
=null;
InBlock.gif        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            out
=new java.io.PrintWriter(new java.io.FileOutputStream("c:\\request.txt",true));
InBlock.gif            out.println(msg);
InBlock.gif            out.close();
ExpandedSubBlockEnd.gif         }

InBlock.gif         
catch(Exception e)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif             out.close();
ExpandedSubBlockEnd.gif         }
          
ExpandedSubBlockEnd.gif    }
    
ExpandedBlockEnd.gif}

None.gif    
None.gif        

在MyRequestListener中,实现了对客户端请求和请求中参数设置的监听。要实现这二个监听功能,需要实现ServletRequestListener和ServletRequestAttributeListener接口 。
如果在本机访问 ,
则直接调用 http://127.0.0.1:8088/test/display.jsp页面,如果在另外机子上访问,则出现登录界面 index.jsp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值