日期:2014-05-17 浏览次数:20731 次
package Servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UpdateCounter extends HttpServlet { public void init() throws ServletException{} public void destroy() { super.destroy(); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/xml"); resp.setCharacterEncoding("UTF-8"); PrintWriter out =resp.getWriter(); //创建一个随机数发生器 Random rmd = new Random(); //create return client's 统计数据xml文档 out.println("<response>"); //product 6 data as 实时的数据统计 for(int i=0; i<6; i++) { out.println("<counter>"+rmd.nextInt(100)+"</counter>");//随机挑选一个0到100的数字 } out.println("</response>"); out.flush(); out.close(); } }
<servlet> <servlet-name>UpdateCounter</servlet-name> <servlet-class>servlet.UpdateCounter</servlet-class> </servlet> <servlet-mapping> <servlet-name>UpdateCounter</servlet-name> <url-pattern>/UpdateCounter</url-pattern> </servlet-mapping>
<!DOCTYPE html> <html> <head> <title>counterHtml.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <script language="javascript"> //定义一个变量用来存储xmlHttpRequest对象 var xmlHttp; //该函数用于创建一个xmlHttpRequest对象 function createXMLHttpRequest() { if(window.ActiveXObject) { xmlHttp = new window.ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } //这是一个通过ajax刷新统计图的方法 function autoFlush() { //创建日期变量时间变量 var tempTime = new Date(); var tempParameter = tempTime.getTime(); //创建一个xmlHttpRequest对象 createXMLHttpRequest(); //将状态触发器绑定到一个函数 xmlHttp.onreadystatechange=processor; //这里放置一个时间参数是为了让服务器知道这是一个新的请求 xmlHttp.open("GET","UpdateCounter?rmd="+tempParameter); //请求发送 xmlHttp.send(null); } //处理从服务器返回的xml文档 function processor() { //定义一个变量用于存储从服务器返回的结果 var result; if(xmlHttp.readyState==4)//如果响应完成 { if(xmlHttp.status==200)//如果返回成功 { //取出服务器返回的