DWR3+spring mvc实现

前篇介绍了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.coreware.dwr.MessagePush">  
</bean>

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

package com.coreware.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
@RemoteProxy
public class MessagePush {
	private String userName;

	public void onPageLoad(final String tag) {
		System.out.println("onPageLoad...");
		// 获取当前的ScriptSession
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("tag", tag);
		userName=tag;
		System.out.println("userName="+userName);
	}
	
	@RemoteMethod
	public 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);
				// 得到所有ScriptSession
				Collection<ScriptSession> sessions = DWRScriptSessionListener.getScriptSessions();
				// 遍历每一个ScriptSession
				for (ScriptSession scriptSession : sessions) {
					scriptSession.addScript(script);
				}
			}
		};
		// 执行推送
		Browser.withAllSessionsFiltered(filter, run); //注意这里调用了有filter功能的方法
	}
}

这样即可实现

你可能感兴趣的:(java,spring,mvc,DWR)