第一步:加载DWR的jar包 dwr.jar

第二部:在web.xml文件中配置

    <!-- dwr配置开始 -->
 <servlet>
  <servlet-name>dwr-invoker</servlet-name>
  <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  <init-param>
   <param-name>debug</param-name>
   <param-value>true</param-value>
  </init-param>
  <init-param>
   <param-name>logLevel</param-name>
   <param-value>ERROR</param-value>
  </init-param>
  <init-param>
   <param-name>crossDomainSessionSecurity</param-name>
   <param-value>false</param-value>
  </init-param>
  <init-param>
   <param-name>allowScriptTagRemoting</param-name>
   <param-value>true</param-value>
  </init-param>
  <init-param>
   <param-name>classes</param-name>
   <param-value>java.lang.Object</param-value>
  </init-param>
  <!-- 开启反转Ajax 即所谓推技术 -->
  <init-param>
   <param-name>activeReverseAjaxEnabled</param-name>
   <param-value>true</param-value>
  </init-param>
   <init-param>
       <param-name>initApplicationScopeCreatorsAtStartup</param-name>
       <param-value>true</param-value>
     </init-param>
  <init-param>
     <param-name>maxWaitAfterWrite</param-name>
     <param-value>1000</param-value>
  </init-param>
  <load-on-startup>3</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>InitScriptSession</servlet-name>
  <servlet-class>com.**.InitScriptSession</servlet-class>
  <load-on-startup>5</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>InitScriptSession</servlet-name>
  <url-pattern>*.action</url-pattern>
 </servlet-mapping>
 <!-- dwr配置結束 -->

红色的是写的一个创建和销毁监听

/**
 * ScriptSession创建和销毁监听
 *
 */
public class InitScriptSession extends GenericServlet {  
  
private static final long serialVersionUID = -905439165340663962L;
private static final String DWR_USER_ID = "DWR_USERID_WANG_XXXX";

ServletContext application;  
  
    public void init() {  
        Container container = ServerContextFactory.get().getContainer();  
        ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);  
        ScriptSessionListener listener = new ScriptSessionListener(){
        //创建
            public void sessionCreated(ScriptSessionEvent ev) {  
                Long userId = Long.parseLong(CookieUtil.getCookieValueByName(WebContextFactory.get().getHttpServletRequest()));
                ScriptSession scriptSession = ev.getSession();  
                scriptSession.setAttribute(DWR_USER_ID, userId);  
            }  
            
            //销毁
            public void sessionDestroyed(ScriptSessionEvent ev) {  
                ev.getSession().getId();  
            }  
        };  
        manager.addScriptSessionListener(listener);  
    }  
  
    public void service(ServletRequest req, ServletResponse res) {  
        init();  
    }  
}  


第三步:在spring定时器中写一个定时器定时到这个方法

//推送过期信息给用户,告诉用户去处理过期
public void pushOverWorder()throws SQLException, BOException{


try{
log.error("开始执行过期信息推送任务!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
WorkOrder order = new WorkOrder();
//order.setA_uid(1);
List sourcePrewarningList = workOrderManage.getMyStatus_out(order);

Map prewarningUserMap = new HashMap();
List chkPrewarningUserList = new ArrayList();
for(int i=0;i<sourcePrewarningList.size();i++){
Map sourcePrewarningMap = (Map) sourcePrewarningList.get(i);
Long prewarningUser = (Long) sourcePrewarningMap.get("a_uid");
if(chkPrewarningUserList.contains(prewarningUser)){
//在列表中存在
//已存在,则更新
        List tmpPrewarningUserList = (List) prewarningUserMap.get(prewarningUser);
        tmpPrewarningUserList.add(sourcePrewarningMap);
        prewarningUserMap.put(prewarningUser, tmpPrewarningUserList);
}else{
//在列表中不存在
chkPrewarningUserList.add(prewarningUser);
List prewarningUserList = new ArrayList();
prewarningUserList.add(sourcePrewarningMap);
prewarningUserMap.put(prewarningUser, prewarningUserList);
}
}
//推动消息
Set set=prewarningUserMap.entrySet();
Iterator sendIterator=set.iterator();
while(sendIterator.hasNext()){
          Entry mapentry = (Entry) sendIterator.next();
          Long tmpPrewarningUser = (Long) mapentry.getKey();
          List tmpPrewarningUserList = (List) mapentry.getValue();
          JSONArray jsonArr = JSONArray.fromObject(tmpPrewarningUserList);
  String messageDate = jsonArr.toString();
//   System.out.println(messageDate);
  MessagePushUtil messagePushUtil = new MessagePushUtil();
  messagePushUtil.sendMessageAuto1(tmpPrewarningUser, messageDate);
    } 
log.error("执行推送任务结束!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}catch (Exception e) {
log.error("执行推送任务失败.", e);
throw new BOException("执行推送任务失败", e);
}
}

第四步:在main.jsp页面进行使用dwr引入

<script type="text/javascript" src="${base}/dwr/engine.js"></script>
<script type="text/javascript" src="${base}/dwr/util.js"></script>

<script type="text/javascript">
$(document).ready(function(){
dwr.engine.setActiveReverseAjax(true);
dwr.engine.setNotifyServerOnPageUnload(true);
});
        function showWorkOrderMessage(retDate){
          var jdata = eval("("+retDate+")");
          var length = jdata.length;
          var hrefData = "";
          hrefData+="<b>您有【"+length+"】条已经超时,请尽快处理</b></br>";
          hrefData+="名称&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 截止时间</br>";
          $.each(jdata, function(index, item){
          //预警状态
          var prewarningStatus = item.status;
          var name = item.name;
          var details_id = item.details_id;
          var endtime = item.endtime;
          var timees = endtime.time;
          var endtime1= date2str(new Date(timees),"yyyy-MM-dd hh:mm:ss")
          if(prewarningStatus=="-1"){//待分配分所负责人
          hrefData+="<a href='${base}/worder/workorder!getWorkorderById.action?details_id="+details_id+"' style='color:#2d64b3; text-decoration:none; font-weight:bold;'>"+name+"</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+endtime1+"</br>";
          }
});
if(hrefData!=""){
$.messager.lays(300, 200);
$.messager.show('超时提醒', hrefData, 15000);
}
        }
        
        function date2str(x,y) {
  var z = {M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
y = y.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)});
return y.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)});
}

</script>


到这基本上已经完成了dwr的推送信息

这完全是我在项目中使用到的一些配置和方法,具体的应用要看系统架构的设计以及你的需求而定,这里没有介绍spring的定时配置,若想了解可以进入Spring定时器配置这里讲的很详细,有什么不懂可以给我发信息358471559


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐