前端之家收集整理的这篇文章主要介绍了
dwr3.0反ajax消息推送,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
web.xml
<!-- dwr ajax -->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>
org.directwebremoting.spring.DwrSpringServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<!-- cause dwr js load error? -->
<init-param>
<param-name>config</param-name>
<param-value>WEB-INF/config/dwr/dwr.xml</param-value>
</init-param>
<load-on-startup>4</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
/**
*消息推送。 向页面推送消息
* @param msg
*/
public void send(Map<String,String> map) {
final Map<String,String> autoMsg = map;
String page = ServerContextFactory.get().getContextPath() +"/main.jsp";
Browser.withPage(page,//对httpSession和scriptSession进行判断,将消息推送给不同用户
// Browser.withPageFiltered(page,new ScriptSessionFilter() {
// @Override
// public boolean match(ScriptSession session) {
// HttpSession ss = WebContextFactory.get().getSession();
// //无session,不推送消息
// if (ss == null)
// return false;
// else {
// return true;
// }
// }
// },new Runnable() {
ScriptBuffer sBuffer = new ScriptBuffer();
public void run() {
sBuffer.appendCall("show",autoMsg);
Collection<ScriptSession> sessions = Browser.getTargetSessions();
for (ScriptSession scriptSession : sessions) {
scriptSession.addScript(sBuffer);
}
}
});
}
/**
*scriptSession创建和注销
*/
private static final long serialVersionUID = -201306202407420071L;
public void init() throws ServletException {
Container container = ServerContextFactory.get().getContainer();
ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
ScriptSessionListener listener = new ScriptSessionListener() {
public void sessionCreated(ScriptSessionEvent ev) {
HttpSession session = WebContextFactory.get().getSession();
String userId = (String)session.getAttribute("loginUserId");
System.out.println("a ScriptSession is created!");
ev.getSession().setAttribute("userId",userId );
}
public void sessionDestroyed(ScriptSessionEvent ev) {
System.out.println("a ScriptSession is distroyed");
}
};
manager.addScriptSessionListener(listener);
}
//main.jsp<script type="text/javascript"> $(function(){ //允许使用推送技术 dwr.engine.setActiveReverseAjax(true); }); //后台推送的时候调用 function show(dbsyMap){ XXXXX } </script>
原文链接:https://www.f2er.com/ajax/166217.html