jsp页面中,如果没有心短消息,图片静止不动,如果有新消息,则闪烁
- <%@ page language="java" contentType="text/html; charset=utf-8"
- pageEncoding="utf-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>Insert title here</title>
- <script type="text/javascript">
- var xmlreq = false;
- function mail(){
- //创建XMLHttpRequest对象
- if(window.XMLHttpRequest){
- xmlreq = new XMLHttpRequest();
- }else{
- try{
- xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
- }catch(e){
- xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
- }
- }
- xmlreq.open("get","mail.do?dt="+new Date().getTime());//创建HTTP请求
- xmlreq.setRequestHeader("Content-Type",
- "application/x-www-form-urlencoded");
- //注册响应处理函数
- xmlreq.onreadystatechange = execute;
- //发送请求
- xmlreq.send(null);
- }
- function execute(){
- if(xmlreq.readyState == 4){
- if(xmlreq.status == 200){
- var msg = xmlreq.responseText;
- if(msg>0){
- document.getElementById("img").src="imgs/mail1.gif";
- }else{
- document.getElementById("img").src="imgs/mail.gif";
- }
- document.getElementById("msg").innerHTML = msg;
- }else{
- document.getElementById("msg").innerHTML = "处理失败!";
- }
- }
- }
- setInterval(mail,2000); //设置每2秒发送一遍请求
- function openMail(){
- window.location="openMail.do";
- }
- </script>
- </head>
- <body>
- welcome!scott!
- <%if(request.getAttribute("num")!=null) {
- %>
- <img src="imgs/mail.gif" id="img" width="20" height="10" onclick="openMail()" style="cursor:hand"></img>(
- <span id="msg">
- <%
- out.print(request.getAttribute("num"));
- }
- %></span>)
- </body>
- </html>
后台处理逻辑:
- PrintWriter out = response.getWriter();
- int num=dao.selectMail();//从数据库中读取出没有阅读的短消息的数量
- out.print(num);//发送到页面