DWR3+spring mvc实现

来源:互联网 发布:大数据产业分析报告 编辑:程序博客网 时间:2024/05/23 15:36

前篇介绍了dwr3的用法,需要的童学请移步到这里:http://blog.csdn.net/tiantang_1986/article/details/50427971

这里在前篇的基础上介绍下dwr3与spring mvc的结合使用

修改一下dwr.xml的配置,把creator="new" 换成creator="spring",name="class"换成name="beanName"

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE dwr PUBLIC    "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"    "http://www.getahead.ltd.uk/dwr/dwr30.dtd"><dwr><allow><create creator="spring" javascript="MessagePush"><param name="beanName" value="MessagePush" /></create></allow></dwr> 

在applicationContext.xml配置里面把主类加载一次,添加下面的配置即可

<bean id="MessagePush" class="com.mysite.dwr.MessagePush">  </bean>

MessagePush做少少的改动,只要是添加一些注解@Controller、@RemoteProxy、@RemoteMethod

package com.mysite.dwr;import java.util.Collection;import java.util.HashMap;import java.util.Map;import org.directwebremoting.Browser;import org.directwebremoting.ScriptBuffer;import org.directwebremoting.ScriptSession;import org.directwebremoting.ScriptSessionFilter;import org.directwebremoting.WebContextFactory;import org.directwebremoting.annotations.RemoteMethod;import org.directwebremoting.annotations.RemoteProxy;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;@Controller@RemoteProxypublic class MessagePush {private String userName;public void onPageLoad(final String tag) {System.out.println("onPageLoad...");// 获取当前的ScriptSessionScriptSession scriptSession = WebContextFactory.get().getScriptSession();scriptSession.setAttribute("tag", tag);userName=tag;System.out.println("userName="+userName);}@RemoteMethodpublic void send(String content){System.out.println("content="+content);// 过滤器ScriptSessionFilter filter = new ScriptSessionFilter() {public boolean match(ScriptSession scriptSession) {String tag = (String) scriptSession.getAttribute("tag");System.out.println("tag="+tag);return userName.equals(tag);}};Runnable run = new Runnable() {private ScriptBuffer script = new ScriptBuffer();public void run() {System.out.println("run....");// 设置要调用的 js及参数script.appendCall("show", content);// 得到所有ScriptSessionCollection<ScriptSession> sessions = DWRScriptSessionListener.getScriptSessions();// 遍历每一个ScriptSessionfor (ScriptSession scriptSession : sessions) {scriptSession.addScript(script);}}};// 执行推送Browser.withAllSessionsFiltered(filter, run); //注意这里调用了有filter功能的方法}}

这样即可实现

0 0
原创粉丝点击