---
title: "ajax+jsp提取数据库记录并实现自动刷新页面"
author: "wanglihu"
date: "2008-09-07T15:54:59Z"
tags: []
slug: "ajax-jsp"
draft: false
lastmod: "2008-09-07T15:54:59Z"
id: 238102
url: "https://wanglihu.iteye.com/blog/238102"
---

在web网站开发中，网页自动刷新的需求及功能已经屡见不鲜了，传统的用整体页面的刷新效果的实现对于网络速度受限的情况下显得就好些得不偿失了！
    这里将介绍一种使用Ajax技术实现网页的局部刷新的功能，只更新局部数据，而非页面全部，详细的源代码请如下所示吧:
其中，本人使用mysql数据库，news表的表结构为：
size=large]<span style="color:red">描述          名称       是否为空     是否主键
新闻编号      newsId    Not Null     P
新闻内容      newsName  Not Null     
备注          BZ        Null  </span>     
首先：新建index.jsp如下：
<%@ page contentType="text/html; charset=gbk" language="java" %>
<html>
<HEAD><TITLE>用户登录页面</TITLE>
<script type="text/javascript">
var xmlHttp;
var id;
function trim(str)      
{      
    var t = str.replace(/(^\s*)|(\s*$)/g, "");  // 用正则表达式将前后空格        
    return t.replace(/(^　*)|(　*$)/g, "");        // 用空字符串替代。      
} 
function createXMLHttpRequest(){
   if(window.ActiveXObject){
     xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   else if(window.XMLHttpRequest){
      xmlHttp=new XMLHttpRequest();
   } 
}
function validate(){
   createXMLHttpRequest();
   var url="Del1.jsp";
   xmlHttp.open("GET",url,true);
   xmlHttp.onreadystatechange=callback;
   xmlHttp.send(null); 
}
function callback(){
   if(xmlHttp.readyState==4){
   		show();
       setTimeout("validate()",3600);
   }
}
function show(){
   var xmlDoc=xmlHttp.responseXML;
   var yan=xmlDoc.getElementsByTagName("content");
   var ta="";
      for(var i=0;i<yan.length;i++){
      var y=yan*;
      var name=y.childNodes.firstChild.data;
          ta+="<tr><td WIDTH=100% height=20><table width=100% height=100% cellpadding=0 cellspacing=0 border=0><tr><td>&nbsp;&nbsp;"+name+"</td><td width=20% nowrap align=right></td></tr></table></td></tr>";
	 }
   document.getElementById("res").innerHTML=ta;
 }



 function startmarquee(lh,speed,delay) {
 validate();
  var p=false;
  var t;
  var o=document.getElementById("res");
  o.innerHTML+=o.innerHTML;
  o.style.marginTop=0;
  o.onmouseover=function(){p=true;}
  o.onmouseout=function(){p=false;}

  function start(){
  t=setInterval(scrolling,speed);
  if(!p) o.style.marginTop=parseInt(o.style.marginTop)-1+"px";
  }

  function scrolling(){
   if(parseInt(o.style.marginTop)%lh!=0){
    o.style.marginTop=parseInt(o.style.marginTop)-1+"px";
    if(Math.abs(parseInt(o.style.marginTop))>=o.scrollHeight/2) o.style.marginTop=0;
   }else{
    clearInterval(t);
    setTimeout(start,delay);
   }
  }

  setTimeout(start,delay);
 }
</script>
</head>
<BODY onLoad="startmarquee(90-18,40,0)">
<table height=44 cellSpacing=0 cellPadding=0 width=870 align=center bgColor=#ffffff border=0>
    <tr>
      <td vAlign=center align=middle>
        <table height=33 cellSpacing=1 cellPadding=0 width=860 align=center border=0>
          <tr>
            <td vAlign=center >
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <font color="red" >${loginmessage } </font><form name="logform" action="/login.do" method="post">
                   &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;用户名：<Input style="FONT-WEIGHT: bold; FONT-SIZE: 11px; COLOR: #cc6600; FONT-FAMILY: Verdana; BACKGROUND-COLOR: #f9f9f9" tabIndex=1 size=13 name="username">
                  密码：<Input style="FONT-WEIGHT: bold; FONT-SIZE: 11px; COLOR: #cc6600; FONT-FAMILY: Verdana; BACKGROUND-COLOR: #f9f9f9" tabIndex=1 type=password size=13 value="" name="password">
                   <Input class="button2" type="submit" value=口令登录 name=B12 >
                      <Input class="button2" type="reset" value=重置 name=reset2 >
                      &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
					  </form>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
<div id="res"></div>
</BODY>
</html>
然后，新建Conn.jsp，用于每个页面调用：
<%@ page contentType="text/html; charset=utf-8" import="java.sql.*, javax.naming.Context, javax.naming.InitialContext"
	errorPage=""%>
<%!Connection conn = null;
	Statement stmt = null;
	ResultSet rs = null;

	public void jspInit() {
		try {
			//Class.forName("com.mysql.jdbc.Driver");
			//建立连接
			//conn = DriverManager.getConnection(
			//		"jdbc:mysql://localhost:3306/SKY5", "root", "123456");
			Context initCtx = new InitialContext();
			Context ctx = (Context) initCtx.lookup("java:comp/env");
			//获取连接池对象
			Object obj = (Object) ctx.lookup("jdbc/javasky");
			//类型转换
			javax.sql.DataSource ds = (javax.sql.DataSource) obj;
			conn = ds.getConnection();
			stmt = conn.createStatement();
		} catch (Exception ex) {
			System.out.println(ex.toString());
		}
	}

	public void Exec(String sql) {
		jspInit();
		try {
			stmt.executeUpdate(sql);
		} catch (Exception e) {
			System.out.print(e.toString());
		}
	}

	public ResultSet getRs(String sql) throws SQLException {
		jspInit();
		try {
			rs = stmt.executeQuery(sql);
			return rs;
		} catch (Exception e) {
			System.out.print(e);
			return null;
		}
	}

	public ResultSet executeQuery(String sql) throws Exception {
		jspInit();
		try {
			sql = new String(sql.getBytes("GBK"), "ISO8859_1");
			stmt = conn.createStatement(
					java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
					java.sql.ResultSet.CONCUR_READ_ONLY);
			rs = stmt.executeQuery(sql);
		} catch (SQLException ex) {
			System.out.println("sql.executeQuery:" + ex.getMessage());
		}
		return rs;
	}

	public String getS(String Str) {
		try {
			byte b = Str.getBytes("ISO-8859-1");
			Str = new String(b, "UTF-8");
		} catch (Exception ee) {
			ee.printStackTrace();
		}
		return Str;
	}%>
其次，新建Del1.jsp如下：
<%@ page contentType="text/html; charset=utf-8" import="java.sql.*,java.util.*" errorPage="" %>
<%@ include file="Conn.jsp" %>
<%
  try{
  ResultSet rs=getRs("select * from news order by newsId desc");
  StringBuffer content=new StringBuffer(""); 
  response.setContentType("text/xml"); 
  response.setHeader("Cache-Control","no-cache");
  content.append("<?xml version=\"1.0\"   encoding=\"UTF-8\" ?>");
  content.append("<contents>");
    while(rs.next()){
    String newsName=rs.getString("newsName");
     content.append("<content>");
     content.append("<name>"+ newsName +"</name>");
     content.append("</content>");
     }
   content.append("</contents>");
   out.print(content);
  }
 catch(Exception e){
      e.printStackTrace();
   }
%>
最后在web.xml配置文件中加入如下内容：
 <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
这样就完成了自动刷新页面的功能，当访问index.jsp首页时，将自动显示news表中所有newsName的数据，当该数据表中新增数据时，首页面将自动将之显示给用户，这样也为用户提供了方便，不用再刷新整个页面！