Ajax案例

来源:互联网 发布:linux软件防火墙排名 编辑:程序博客网 时间:2024/04/29 07:34

数据库采用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>

原创粉丝点击