当前位置:首页 > 开发 > Web前端 > Ajax > 正文

Ajax案例

发表于: 2009-07-27   作者:gongmeitao   来源:转载   浏览:
摘要: 数据库采用Sql Server2005 项目名称为:Ajax_Demo 1.com.demo.conn包 package com.demo.conn; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; //获取数据库连接的类public class DBConnec

数据库采用Sql Server2005

项目名称为:Ajax_Demo

1.com.demo.conn包

package com.demo.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

//获取数据库连接的类
public class DBConnection {

//进行数据库的连接的方法
public static Connection getConnection()
{
Connection conn=null;

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=BookShop", "sa", "sa");

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

}

2.com.demo.model包

package com.demo.model;

public class Book {

private Integer id;

private String title;

private Double money;

private Integer click;

private String isbn;

private int wordCount;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public Double getMoney() {
return money;
}

public void setMoney(Double money) {
this.money = money;
}

public Integer getClick() {
return click;
}

public void setClick(Integer click) {
this.click = click;
}

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public int getWordCount() {
return wordCount;
}

public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
}

3.com.demo.dao包

package com.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.demo.conn.DBConnection;
import com.demo.model.Book;

public class NewBookDAO {

private Connection conn=null;
private ResultSet rs=null;

//构造方法
public NewBookDAO()
{
conn=DBConnection.getConnection();
}

//1.查询第一条书籍的ISBN
public String findBookByISBN()
{
String select_sql="select isbn from newBooks where id=4939";
String isbn=null;
try {
PreparedStatement pstm=conn.prepareStatement(select_sql);
rs=pstm.executeQuery();
while(rs.next())
{
isbn=rs.getString("isbn");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return isbn;
}

//查询一条数据[即Object]
public Book findBookById(int id)
{
String sql="select * from newBooks where id=?";
Book book=new Book();

try {
PreparedStatement pstm=conn.prepareStatement(sql);
pstm.setInt(1, id);
rs=pstm.executeQuery();

if(rs.next())
{
book.setId(new Integer(rs.getInt("id")));
book.setTitle(rs.getString("title"));
book.setMoney(new Double(rs.getDouble("unitPrice")));
book.setClick(new Integer(rs.getInt("clicks")));
book.setIsbn(rs.getString("isbn"));
book.setWordCount(rs.getInt("wordscount"));

rs.close();
return book;
}
else
{
rs.close();
return null;
}


} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}


//查询几条数据[即List结合]
public List findBook()
{
ArrayList array=new ArrayList();
String sql="select top 10 * from newBooks";

try {
PreparedStatement pstm=conn.prepareStatement(sql);

rs=pstm.executeQuery();

while(rs.next())
{
Book book=new Book();
book.setId(new Integer(rs.getInt("id")));
book.setTitle(rs.getString("title"));
book.setMoney(new Double(rs.getDouble("unitPrice")));
book.setClick(new Integer(rs.getInt("clicks")));
book.setIsbn(rs.getString("isbn"));
book.setWordCount(rs.getInt("wordscount"));

array.add(book);
}

rs.close();

return array;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return array;
}

public static void main(String[] args) {
NewBookDAO bookDao=new NewBookDAO();
List lst=bookDao.findBook();
System.out.println(lst.size());

}
}

4.com.demo.control包

package com.demo.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.demo.dao.NewBookDAO;
import com.demo.model.Book;

public class BookServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

// 设置输出的信息的格式及字符集
response.setContentType("text/xml; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");

// 调用DAO层中的方法
NewBookDAO bookDao = new NewBookDAO();

PrintWriter writer = response.getWriter();

///////////////////////////////////////////////
// 读取一个字段的字符串
String isbn = bookDao.findBookByISBN();

//////////////////////////////////////////////
// 返回一个对象
//Book obj = bookDao.findBookById(4948);
//
//writer.write("<Book>");
//writer.println("<id>" + obj.getId() + "</id>");
//writer.println("<title>" + obj.getTitle() + "</title>");
//writer.println("<unitPrice>" + obj.getMoney() + "</unitPrice>");
//writer.println("<clicks>" + obj.getClick() + "</clicks>");
//writer.println("<isbn>" + obj.getIsbn() + "</isbn>");
//writer.println("<wordscount>" + obj.getWordCount()+ "</wordscount>");
//writer.write("</Book>");
// writer.close();

//////////////////////////////////////////////
// 返回一个集合
List lst = bookDao.findBook();

writer.write("<Books>");
for(int i=0;i<lst.size();i++)
{
Book obj=(Book)lst.get(i);

writer.write("<Book>");
writer.println("<id>" + obj.getId() + "</id>");
writer.println("<title>" + obj.getTitle() + "</title>");
writer.println("<unitPrice>" + obj.getMoney() + "</unitPrice>");
writer.println("<clicks>" + obj.getClick() + "</clicks>");
writer.println("<isbn>" + obj.getIsbn() + "</isbn>");
writer.println("<wordscount>" + obj.getWordCount()+ "</wordscount>");
writer.write("</Book>");


}
writer.write("</Books>");

writer.close();
}

}

表示层:jsp页面(index.jsp)

页面内容为:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
var xmlHttp=null;
//创建一个交互的XmlHttpRequest对象
function createXMLHttpRequest()
{
if(window.XmlHttpRequest)
{
xmlHttp=new XmlHttpRequest();
}

if(window.ActiveXObject)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp=new ActiveXObject("msxml2.XMLHTTP");
}
}
}

//交互的方法
function testAjax()
{
createXMLHttpRequest();

if(xmlHttp!=null)
{
xmlHttp.onreadystatechange=showArray;
xmlHttp.open("GET","BookServlet",true);
xmlHttp.send(null);
}
}

//实现一个字符串的数据显示
function showData()
{
if(xmlHttp.readyState==4&&xmlHttp.status==200)
{
//alert(xmlHttp.responseText);
document.getElementById("div_content").innerHTML="";
document.getElementById("div_content").innerHTML=xmlHttp.responseText;
}
}

//实现一个对象的数据显示
function showObject()
{
if(xmlHttp.readyState==4&&xmlHttp.status==200)
{
//alert(xmlHttp.responseText);

document.getElementById("div_contentObj").innerHTML="";
var id=xmlHttp.responseXml.getElementsByTagName("id")[0].firstChild.data;
var title=xmlHttp.responseXml.getElementsByTagName("title")[0].firstChild.data;
var unitPrice=xmlHttp.responseXml.getElementsByTagName("unitPrice")[0].firstChild.data;
var clicks=xmlHttp.responseXml.getElementsByTagName("clicks")[0].firstChild.data;
var isbn=xmlHttp.responseXml.getElementsByTagName("isbn")[0].firstChild.data;
var wordscount=xmlHttp.responseXml.getElementsByTagName("wordscount")[0].firstChild.data;
document.getElementById("div_contentObj").innerHTML=id+title+unitPrice+clicks+isbn+wordscount;
}
}

//实现一个集合的数据显示
function showArray()
{
if(xmlHttp.readyState==4&&xmlHttp.status==200)
{
document.getElementById("div_contentArray").innerHTML="";
var txt="";
var ele=xmlHttp.responseXml.documentElement.getElementsByTagName("Book");

for(var i=0;i<ele.length;i++)
{
xx=ele[i].getElementsByTagName("id");
{
txt=txt+xx[0].firstChild.nodeValue;
}
xx=ele[i].getElementsByTagName("title");
{
txt=txt+"---"+xx[0].firstChild.nodeValue+"<br>";
}

}
document.getElementById("div_contentArray").innerHTML=txt;
}
}
</script>
<style type="text/css">
#div_content
{
border:solid gray 1px;
height:100px;
width:200px;
}
#div_contentObj
{
border:solid gray 1px;
height:100px;
width:210px;
}
#div_contentArray
{
border:solid gray 1px;
height:100px;
width:500px;
}
</style>
</head>

<body>
<input type="button" name="btn_ajx" value="Ajax显示字符串数据" onclick="testAjax()">
<br>
<div id="div_content"></div>
<hr>
<input type="button" name="btn_ajxObj" value="Ajax显示对象数据" onclick="testAjax()">
<br>
<div id="div_contentObj"></div>
<hr>
<input type="button" name="btn_ajxArray" value="Ajax显示结合数据" onclick="testAjax()">
<div id="div_contentArray"></div>
</body>
</html>

版权声明:本文为博主原创文章,未经博主允许不得转载。

Ajax案例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
1.AJAX = 异步 JavaScript 及 XML(Asynchronous JavaScript and XML) AJAX 不是一种新的编程语言
同事问我,咱们从数据库里面获取数据,用ajax的方式展示到前台页面。啥都不说了,动手写个案例吧。
请求的ajax路径传递的参数(data)会到action中被一个同样名字的变量(附带set get方法)接收,返回的da
近期项目中有好几次用到多图上传,第一次在项目中真正用到Ajax技术,稍微整理了下,贴个案例出来。
5 案例
在过去的几年中,不断涌现出的新的自定义网站设计技术。一个非常流行的想法是把所有的主要内容放在
摘要 本文将从完成“输入数据验证”这个功能出发,逐渐展开ASP.NET MVC与Ajax结合的方法。首先,本
摘要 本文将从完成“输入数据验证”这个功能出发,逐渐展开ASP.NET MVC与Ajax结合的方法。首先,本
CAS Software AG是来自德国Karlsruhe的一家软件公司,创建于1986年。该公司专注于CRM(客户关系管理
因为是一个问答网站,所以每个页面都可以随时提问, 所以我们将提问按钮功能放到header.ejs头文件中
Cas自定义登录页面Ajax实现:http://cydiay.iteye.com/blog/1738713 CAS 之 跨域 Ajax 登录实践:htt
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号