ajax+jsp提取数据库记录并实现自动刷新页面

在web网站开发中,网页自动刷新的需求及功能已经屡见不鲜了,传统的用整体页面的刷新效果的实现对于网络速度受限的情况下显得就好些得不偿失了!
这里将介绍一种使用Ajax技术实现网页的局部刷新的功能,只更新局部数据,而非页面全部,详细的源代码请如下所示吧:
其中,本人使用mysql数据库,news表的表结构为:
size=large][color=red]描述 名称 是否为空 是否主键
新闻编号 newsId Not Null P
新闻内容 newsName Not Null
备注 BZ Null [/color][size]
首先:新建index.jsp如下:
<%@ page contentType="text/html; charset=gbk" language="java" %>

用户登录页面













           ${loginmessage }

           用户名:
密码:


           






然后,新建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("");
content.append("");
while(rs.next()){
String newsName=rs.getString("newsName");
content.append("");
content.append(""+ newsName +"");
content.append("
");
}
content.append("
");
out.print(content);
}
catch(Exception e){
e.printStackTrace();
}
%>
最后在web.xml配置文件中加入如下内容:

index.jsp

这样就完成了自动刷新页面的功能,当访问index.jsp首页时,将自动显示news表中所有newsName的数据,当该数据表中新增数据时,首页面将自动将之显示给用户,这样也为用户提供了方便,不用再刷新整个页面!

你可能感兴趣的:(Ajax技术)