DWR2.x的推技术也叫DWR Reverse Ajax(逆向Ajax)主要是在BS架构中,从服务器端向多个浏览器主动推数据的一种技术。在DWR所开的线程中使用Reverse Ajax时,经过WebContextFactory.get()获取WebContext对象,进而获取脚本Session。
在DWR以外使用Reverse Ajax时,就要用到ServerContext,在Spring环境中要获得ServerContext,就须要用到Spring的ServletContextAware接口。javascript
Reverseeverse Ajax的实现有3种方式:
DWR的逆向Ajax两种模式:主动模式和被动模式,其中主动模式包括polling和comet两种,被动模式只有piggyback这一种。html
1)piggyback方式java
这是默认的方式。若是后台有什么内容须要推送到前台,是要等到那个页面进行下一次ajax请求的时候,将须要推送的内容附加在该次请求以后,传回到页面。只有等到下次请求页面主动发起了,中间的变化内容才传递回页面。web
2)comet方式ajax
当服务端创建和浏览器的链接,将页面内容发送到浏览器以后,对应的链接并不关闭,只是暂时挂起。若是后面有什么新的内容须要推送到客户端的时候直接经过前面挂起的链接再次传送数据。服务器所能提供的链接数目是必定的,在大量的挂起的链接没有关闭的状况下,可能形成新的链接请求不能接入,从而影响到服务质量。浏览器
3)polling方式服务器
由浏览器定时向服务端发送ajax请求,询问后台是否有什么内容须要推送,有的话就会由服务端返回推送内容。这种方式和咱们直接在页面经过定时器发送ajax请求,而后查询后台是否有变化内容的实现是相似的。只不过用了dwr以后这部分工做由框架帮咱们完成了。session
使用DWR的推技术的步骤架构
1)在web.xml文件中增长如下配置信息app
dwr-invoker
uk.ltd.getahead.dwr.DWRServlet
debug
true
pollAndCometEnabled
true
1
dwr-invoker
/dwr/*
2)dwr.xml配置:
3)java bean:
public class Message {
private long id = System.currentTimeMillis();
private String text;
public Message(){
}
public Message(String newText){
text = newText;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
4)dwrHelper类:
public class DWRHelper {
private static LinkedList messages = new LinkedList();
private static ReentrantLock lock = new ReentrantLock(); //JDK5锁
public void addMessage(String text){
try{
lock.lock();
if(text!=null && text.trim().length()>0){
messages.addFirst(new Message(text));
if(messages.size()>10){
messages.removeLast();
}
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
lock.unlock();
}
//得到DWR上下文
WebContext webContext = WebContextFactory.get();
//获取当前页面URL,好比/ext3/test_tag.jsp
String currentPage = webContext.getCurrentPage();
//当前脚本sessin
ScriptSession scriptSession = webContext.getScriptSession();
//设置页面控件的值
Util util = new Util(scriptSession);
util.setValue("text", ""); //这里是清空页面输入框的值
//设置脚本sessin的属性值
scriptSession.setAttribute("uid", "cjm");
//获取脚本session的属性值
for(Iterator it=scriptSession.getAttributeNames();it.hasNext();){
String attrName = (String)it.next();
System.out.println(attrName + "=" + scriptSession.getAttribute(attrName));
}
//获取全部浏览当前页面的脚本session
Collection sessions = webContext.getScriptSessionsByPage(currentPage);
Util utilAll = new Util(sessions);
//执行客户端脚本
ScriptBuffer script = new ScriptBuffer();
script.appendScript("clientFunction(")
.appendData(scriptSession.getAttribute("uid"))
.appendScript(");");
for(ScriptSession session: sessions){
session.addScript(script);
}
//更新这些脚本session的一些元素
utilAll.removeAllOptions("messages");
utilAll.addOptions("messages", messages, "id", "text");
}
}
5)jsp:
输入信息:
function sendMessage() {
DWRHelper.addMessage(dwr.util.getValue("text"));
}