1.ScriptSession使用中存在的问题
在上一节实现了服务器的推送功能,但是根据
ScriptSession的生命周期我们可以得出以下几点的问题:
(1)ScriptSession不会与HttpSession同时创建
(2)如何得到ScriptSession
在DWR中,我们可以通过WebContextFactory.get()来取得一个WebContext对象,进而通过WebContext的getScriptSession()取得ScriptSession对象。
但是要注意,在我们自定义的Servlet中,我们也可以通过WebContextFactory.get()来取得一个WebContext,但是这种方法却不能取得ScriptSession对象。因为,此WebContext对象其实不是通过DWR的上下文环境得到的,所以,就根本没有创建ScriptSession对象。
假设这种方式也能得到ScriptSession的话,那么我们实现“推”也就可以不局限在DWR的上下文环境中了,那么其灵活性就会大很多了。所以,这就是我们不能在Servlet中实现推的原因。
(3) 关于刷新就创建一个新的ScriptSession问题
在我们需要推送的页面中,如果你刷新一下,那么就提交一个Http的request,此时,如果是第一次,那么就会创建一个httpSession对象,同时,请求由DwrServlet来处理后,就会创建一个ScriptSession.这个ScriptSession会和你的request请求的URI绑定放在一个由ScriptSessionManager维护的Map里面(这里面其实是一个URI对应的Set,在Set里面放置的是URI绑定的所有ScriptSession)。
DWR3.0可以通过
1 |
//得到所有ScriptSession |
2 | Collection<ScriptSession> sessions = browser.getTargetSessions(); |
DWR2.x可以通过
Collection pages = webContext.getScriptSessionsByPage(
"/yourPage.jsp"
);
通过此方法,就可以实现调用客户端的javascript函数,实现对客户端的操作。
(5) 在上面的推送中产生的问题
上面的方法已经可以实现向所有的访问者推送。但是问题是,在客户端,如果用户刷新一次或多次,那么,Collection里面可能就保存了很多的无用的ScriptSession,所以不仅仅会影响性能问题,更重要的是,可能就不能实现你想要的功能。
(5) 在上面的推送中产生的问题
上面的方法已经可以实现向所有的访问者推送。但是问题是,在客户端,如果用户刷新一次或多次,那么,Collection里面可能就保存了很多的无用的ScriptSession,所以不仅仅会影响性能问题,更重要的是,可能就不能实现你想要的功能。
2.如何管理有效的ScriptSession
由于上面的问题,我们就需要自己管理ScriptSession。其实,有效地HttpSession,就是那个和当前的HttpSession匹配的ScriptSession。
在DWR3.0中推出了 ScriptSessionListener用来监听ScriptSession的创建及销毁事件。我们可以使用该监听器来维护我们自己的Map。
1.新建一个类实现
ScriptSessionListener接口
01
package
sugar.dwr;
02
03 | importjava.util.Collection; |
04
java.util.HashMap;
05 | java.util.Map; |
06
07
javax.servlet.http.HttpSession;
08
09
org.directwebremoting.ScriptSession;
10
org.directwebremoting.WebContext;
11 | org.directwebremoting.WebContextFactory; |
12
org.directwebremoting.event.ScriptSessionEvent;
13 | org.directwebremoting.event.ScriptSessionListener; |
14
15
public
class
DWRScriptSessionListener
implements
ScriptSessionListener {
16
17 | //维护一个Map key为session的Id, value为ScriptSession对象 |
18
static
final
Map<String,ScriptSession> scriptSessionMap =
new
HashMap<String,ScriptSession>();
19 |
20
/**
21 | * ScriptSession创建事件 |
22
*/
23 | voidsessionCreated(ScriptSessionEvent event) { |
24
WebContext webContext = WebContextFactory. get();
25 | HttpSession session = webContext.getSession(); |
26
ScriptSession scriptSession = event.getSession();
27 | scriptSessionMap.put(session.getId(),scriptSession);//添加scriptSession |
28
System. out.println(
"session: "
+ session.getId() +
" scriptSession: "
+ scriptSession.getId() +
"is created!"
);
29 | } |
30
31
/**
32
* ScriptSession销毁事件
33 | */ |
34
sessionDestroyed(ScriptSessionEvent event) {
35 | WebContext webContext = WebContextFactory. get(); |
36
HttpSession session = webContext.getSession();
37 | ScriptSession scriptSession = scriptSessionMap.remove(session.getId());//移除scriptSession |
43 | 44 | staticCollection<ScriptSession> getScriptSessions(){ |
45 | returnscriptSessionMap.values(); |
46
}
47 | } |