Ajax 动态刷新例子分析(实现级联更新)
一.目的:
利用SQL Server 自带的pubs 库title表(也可以自己建一个表,id,type,bookname,3个字段呢即可),点击页面类别时,及时动态刷新对应类别的书的书名,效果如下:
二.实现过程
1.写个对应该表的javabean(只有get/set方法对和构筑方法),略。
2.写个类,专门得到连接数据库的connection:
- package db;
- import java.sql.Connection;
- import java.sql.DriverManager;
- public class DBCon {
- private static Connection con ;
- public static Connection getConnection(){
- try {
- Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
- String url = "jdbc:microsoft:sqlserver://localhost:1433;databasename=pubs";
- con = DriverManager.getConnection(url, "sa", "123");
- System.out.println("ok");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return con;
- }
- }
3.写个Dao 的类,能得到所有的书的类别 和 某一类别书的所有书名
- package 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 vo.Book;
- import db.DBCon;
- public class BookDao {
- private Connection con;
- private PreparedStatement pstmt;
- private ResultSet rs;
- //返回书的所有类型,以便动态显示在页面的书的类别下拉框中
- public List selectTypes(){
- List data = new ArrayList();
- con = DBCon.getConnection();
- String sql = "select distinct type from titles";
- try {
- pstmt = con.prepareStatement(sql);
- rs = pstmt.executeQuery();
- while(rs.next()){
- data.add(rs.getString(1));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return data;
- }
- //返回某一类型对应的所有书的书名
- public List selectByType(String type){
- List data = new ArrayList();
- con = DBCon.getConnection();
- String sql = "select title_id,title,price from titles where type=?";
- try {
- pstmt = con.prepareStatement(sql);
- pstmt.setString(1, type);
- rs = pstmt.executeQuery();
- while(rs.next()){
- Book book = new Book();
- book.setTitleid(rs.getString(1));
- book.setTitle(rs.getString(2));
- book.setUnitprice(rs.getFloat(3));
- data.add(book);
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- return data;
- }
- }
4.写个QueryServlet,把书类别传给request;并把某一类别的书名返回给Ajax引擎
- package 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 vo.Book;
- import dao.BookDao;
- public class QueryServlet extends HttpServlet {
- private BookDao bd = new BookDao();
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- PrintWriter out = response.getWriter();
- //根据传过来的参数判断,到底是调用dao的哪个方法
- String act = request.getParameter("act");
- //返回所有类型
- if(act.equals("selectTypes")){
- List typeList = bd.selectTypes();
- request.setAttribute("types", typeList);
- request.getRequestDispatcher("query.jsp").forward(request, response);
- }
- //返回某一类型的书的所有书名
- if(act.equals("selectTitles")){
- String type = request.getParameter("type");
- List list = bd.selectByType(type);
- //System.out.println(list.size()+"种书");
- StringBuffer sb = new StringBuffer();
- for(int i=0;i<list.size();i++){
- Book b =(Book)list.get(i);
- sb.append(b.getTitle()+"|");
- }
- String result = sb.toString();
- //System.out.println(result+"=========");
- //由于out.write只能返回一个字符串,所以将所有书名连接成一个StringBuffer后,再以String返回给ajax引擎
- out.write(result);
- out.close();
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
5. 页面部分
index.jsp直接刷新到query.jsp
里面只需配置一句话:
- <meta http-equiv="refresh" content="0;url=QueryServlet?act=selectTypes">
query.jsp里面是Ajax定义,调用,返回的JS 和页面代码:
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <%
- 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">
- <!--
- //定义ajax引擎
- var xmlRequest;
- function sendRequest(){
- //得到用户名
- var type = document.body.all.type.value;
- //alert(type);
- //创建ajax引擎
- if(window.ActiveXObject){
- //说明浏览器IE
- // alert("浏览器IE");
- xmlRequest = new ActiveXObject("Microsoft.XMLHttp");
- }else{
- //其他浏览器
- xmlRequest = new XMLHttpRequest();
- }
- //判断ajax引擎是否创建成功
- if(xmlRequest){
- //alert("ajax引擎创建成功");
- url ="QueryServlet?act=selectTitles&type="+type;
- //ajax引擎准备发送 true 表示 同步 安全的
- xmlRequest.open("GET",url,true);
- //回调函数
- xmlRequest.onreadystatechange = getResponse;
- //发送
- xmlRequest.send();
- }
- }
- function getResponse(){
- if(xmlRequest.readyState == 4){
- if(xmlRequest.status == 200){
- //从ajax引擎中获取结果
- var result = xmlRequest.responseText;
- //alert(result);
- var titles = result.split("|");
- var t = document.body.all.title;
- t.length = 0;
- for(var i=0;i<titles.length;i++){
- t.options[i] = new Option(titles[i],titles[i]);
- }
- }
- }
- }
- -->
- </script>
- </head>
- <body>
- <h3>书籍查询</h3>
- 书籍类别:
- <select name="type" id="type" onchange="sendRequest();">
- <c:forEach var="t" items="${types}">
- <option value="${t}">${t}</option>
- </c:forEach>
- </select>
- 书籍名称:
- <select name="title">
- </select>
- </body>
- </html>
6..小结