DWR+Spring 全注解 消息推送(按用户)

maven依赖:

<!-- dwr -->
<dependency>
   <groupId>org.directwebremoting</groupId>
   <artifactId>dwr</artifactId>
   <version>3.0.2-RELEASE</version>
</dependency>

-----------------------------------------------------------------------------------------------------------------------------------

web.xml配置(红色部分是需要增加的)

<servlet>
   <servlet-name>springServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:/spring-mvc*.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>springServlet</servlet-name>
   <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
   <servlet-name>springServlet</servlet-name>
   <url-pattern>/dwr/*</url-pattern>
</servlet-mapping

 ---------------------------------------------------------------------------------------------------------------------------------

在上面ContextConfigLocation对应的xml,这里是spring-mvc.xml中配置如下内容。
<!-- dwr相关,使用注解-->
<dwr:configuration/>
<dwr:annotation-config />
<dwr:annotation-scan base-package="com.yooeee.web" scanDataTransferObject="true" scanRemoteProxy="true"/>
<dwr:url-mapping />
<dwr:controller id="dwrController" debug="true">
   <dwr:config-param name="allowScriptTagRemoting" value="true" />
   <dwr:config-param name="crossDomainSessionSecurity" value="false" />
   <dwr:config-param name="classes" value="java.lang.Object"/>
   <dwr:config-param name="activeReverseAjaxEnabled" value="true"/>
   <dwr:config-param name="scriptSessionTimeout" value="3600000" />
   <dwr:config-param name="initApplicationScopeCreatorsAtStartup" value="true" />
   <!--<dwr:config-param name="org.directwebremoting.extend.ScriptSessionManager" value="com.pfxt.util.DWRScriptSessionManager" />-->
</dwr:controller>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="order" value="1" />
</bean>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
   <property name="order" value="2" />
</bean>

<!--必须加这个才可以正常引用到dwr的JS文件-->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="order" value="3" />
   <property value="true" name="alwaysUseFullPath"></property>
   <property name="mappings">
      <props>
         <prop key="/dwr/**">dwrController</prop>
      </props>
   </property>
</bean>
注意命名空间
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xsi:schemaLocation="http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd"
---------------------------------------------------------------------------------------------------------------------------------
页面:
<script src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script src='<%=request.getContextPath()%>/dwr/util.js'></script>  
<!-- Message为在类中注解的名字 -->
<script src="<%=request.getContextPath()%>/dwr/interface/Message.js"></script> 

<script type="text/javascript">
$(document).ready(function(){
    dwr.engine.setActiveReverseAjax(true);
    dwr.engine.setNotifyServerOnPageUnload(true);
    // 一进入页面一定要访问后台与DWR建立长连接,之后这个连接可以在任意地方使用
    Message.onPageLoad();
});

</script>
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xsi:schemaLocation="http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd"
--------------------------------------------------------------------------------------------------------------------------------- 页面:
<script src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script src='<%=request.getContextPath()%>/dwr/util.js'></script>  
<!-- Message为在类中注解的名字 -->
<script src="<%=request.getContextPath()%>/dwr/interface/Message.js"></script> 

<script type="text/javascript">
$(document).ready(function(){
    dwr.engine.setActiveReverseAjax(true);
    dwr.engine.setNotifyServerOnPageUnload(true);
    // 一进入页面一定要访问后台与DWR建立长连接,之后这个连接可以在任意地方使用
    Message.onPageLoad();
});

</script>
--------------------------------------------------------------------------------------------------------------------------------- 业务类 Message.java
@RemoteProxy(name="Message")
public class Message{
    private static final Logger logger = LoggerFactory.getLogger(MerchantTodayOrderController.class);
    /**
     * 与DWR建立长连接。每个连接以userId标识
     */
     @RemoteMethod
     public void onPageLoad() {
        ScriptSession session = WebContextFactory.get().getScriptSession();
        session.setAttribute("userId", UserUtils.getUser().getId());
        System.out.println("页面绑定的 userid:" + session.getAttribute("userId"));
    }
}
 ------------------------------------------------------------------------------------------------------------------------------------ 两个DWR的类。用来管理scriptSession 1、
public class DwrScriptSessionListener implements ScriptSessionListener {

    //维护一个map key为session的id, value为scriptsession对象
     public static final Map<String, ScriptSession> scriptSessionMap = new HashMap<String, ScriptSession>();

    /**
     * scriptsession创建事件
     */
     public void sessionCreated(ScriptSessionEvent event) {
        WebContext webcontext = WebContextFactory. get();
        HttpSession session = webcontext.getSession();
        ScriptSession scriptSession = event.getSession();
        scriptSessionMap.put(session.getId(), scriptSession);     //添加scriptsession
        System.out.println( "session: " + session.getId() + " scriptsession: " + scriptSession.getId() + "is created!");
    }


    /**
     * scriptsession销毁事件
     */
     public void sessionDestroyed(ScriptSessionEvent event) {
        WebContext webcontext = WebContextFactory. get();
        HttpSession session = webcontext.getSession();
        ScriptSession scriptsession = scriptSessionMap.remove(session.getId());  //移除scriptsession
        System.out.println( "session: " + session.getId() + " scriptsession: " + scriptsession.getId() + "is destroyed!");
    }

    /**
     * 获取所有scriptsession
     */
    public static Collection<ScriptSession> getScriptSessions(){
        return scriptSessionMap.values();
    }

}
public class DwrScriptSessionListener implements ScriptSessionListener {

    //维护一个map key为session的id, value为scriptsession对象
     public static final Map<String, ScriptSession> scriptSessionMap = new HashMap<String, ScriptSession>();

    /**
     * scriptsession创建事件
     */
     public void sessionCreated(ScriptSessionEvent event) {
        WebContext webcontext = WebContextFactory. get();
        HttpSession session = webcontext.getSession();
        ScriptSession scriptSession = event.getSession();
        scriptSessionMap.put(session.getId(), scriptSession);     //添加scriptsession
        System.out.println( "session: " + session.getId() + " scriptsession: " + scriptSession.getId() + "is created!");
    }


    /**
     * scriptsession销毁事件
     */
     public void sessionDestroyed(ScriptSessionEvent event) {
        WebContext webcontext = WebContextFactory. get();
        HttpSession session = webcontext.getSession();
        ScriptSession scriptsession = scriptSessionMap.remove(session.getId());  //移除scriptsession
        System.out.println( "session: " + session.getId() + " scriptsession: " + scriptsession.getId() + "is destroyed!");
    }

    /**
     * 获取所有scriptsession
     */
    public static Collection<ScriptSession> getScriptSessions(){
        return scriptSessionMap.values();
    }

}
-------------------------------------------------------------------------------------------------------------------------------------- 2、
@Service
public class DwrScriptSessionManager extends DefaultScriptSessionManager {
    public DwrScriptSessionManager() {
        // 绑定一个scriptsession增加销毁事件的监听器
        this.addScriptSessionListener(new DwrScriptSessionListener());
        System.out.println("bind dwrscriptsessionlistener");
    }
}
------------------------------------------------------------------------------------------------------------------------------------ 发消息的实现:
// DWR 部分
Runnable run = new Runnable(){
   public void run() {
      // 得到所有ScriptSession
      Collection<ScriptSession> sessions = DwrScriptSessionListener.getScriptSessions();
      // Collection<ScriptSession> sessions = Browser.getTargetSessions();
      //logger.warn("得到ScriptSession的个数为" + sessions.size());
      System.out.println("得到ScriptSession的个数为" + sessions.size());
      // 遍历每一个ScriptSession,
      for (ScriptSession scriptSession : sessions){
         System.out.println("从session里拿到绑定的userId为:" + scriptSession.getAttribute("userId"));
         if(scriptSession.getAttribute("userId") != null && userIds.contains(scriptSession.getAttribute("userId"))){
            // 设置要调用的 js及参数
            ScriptBuffer script = new ScriptBuffer();
            // 从redis里拿到每个账号所管理的所有商户的所有订单
            script.appendCall("showMessage" , redisService.getMap(scriptSession.getAttribute("userId").toString()));
            scriptSession.addScript( script);
         }
      }
   }
};
//执行推送
Browser. withAllSessions(run);
 有不明白的可加微信177683698探讨。

猜你喜欢

转载自liyang678.iteye.com/blog/2395009
今日推荐