jsp页面中,如果没有心短消息,图片静止不动,如果有新消息,则闪烁

 

  1. <%@ page language="java" contentType="text/html; charset=utf-8" 
  2.     pageEncoding="utf-8"%> 
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
  4. <html> 
  5. <head> 
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
  7. <title>Insert title here</title> 
  8.  
  9. <script type="text/javascript"> 
  10.     var xmlreq = false;  
  11.     function mail(){  
  12.         //创建XMLHttpRequest对象  
  13.            if(window.XMLHttpRequest){  
  14.                  xmlreq = new XMLHttpRequest();  
  15.            }else{  
  16.                try{  
  17.                      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");  
  18.                   }catch(e){  
  19.                       xmlreq = new ActiveXObject("Microsoft.XMLHTTP");  
  20.                   }  
  21.             }  
  22.            xmlreq.open("get","mail.do?dt="+new Date().getTime());//创建HTTP请求  
  23.             xmlreq.setRequestHeader("Content-Type",  
  24.             "application/x-www-form-urlencoded");  
  25.             //注册响应处理函数  
  26.             xmlreq.onreadystatechange = execute;  
  27.             //发送请求  
  28.             xmlreq.send(null);  
  29.     }     
  30.     function execute(){  
  31.         if(xmlreq.readyState == 4){  
  32.             if(xmlreq.status == 200){  
  33.                var msg = xmlreq.responseText;  
  34.                if(msg>0){  
  35.                    document.getElementById("img").src="imgs/mail1.gif";  
  36.                      
  37.                }else{  
  38.                    document.getElementById("img").src="imgs/mail.gif";  
  39.                }      
  40.                document.getElementById("msg").innerHTML = msg;  
  41.             }else{  
  42.                document.getElementById("msg").innerHTML = "处理失败!";  
  43.             }  
  44.           }  
  45.     }  
  46.     setInterval(mail,2000);  //设置每2秒发送一遍请求
  47.     function openMail(){  
  48.         window.location="openMail.do";  
  49.     }     
  50. </script> 
  51. </head> 
  52. <body> 
  53.     welcome!scott!    
  54.     <%if(request.getAttribute("num")!=null) {  
  55.         %> 
  56.         <img src="imgs/mail.gif" id="img" width="20" height="10" onclick="openMail()" style="cursor:hand"></img>(  
  57.         <span id="msg"> 
  58.         <%   
  59.         out.print(request.getAttribute("num"));  
  60.         }  
  61.         %></span>)  
  62.           
  63. </body> 
  64. </html> 

后台处理逻辑:

 

  1. PrintWriter out = response.getWriter();  
  2. int num=dao.selectMail();//从数据库中读取出没有阅读的短消息的数量  
  3. out.print(num);//发送到页面