AJAX: Asynchronous Javascript and XML
1. 客户端触发异步操作
2. 创建新的XMLHttpRequest, 是重要的js对象,通过它提起对服务器端的请求
3. 与server进行连接
4. 服务器端进行了连接处理
5. 返回包含处理结果的XML文档
6. XMLHttpRequest对象接收处理结果并分析
7. 更新页面
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> <html> <head> <title>www.mldnjava.cn,MLDN高端Java培训</title> <script language="javascript"> var xmlHttp ; var flag = false ; function createXMLHttp(){ if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest() ; } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") ; } } function checkUserid(userid){ createXMLHttp() ; xmlHttp.open("POST","CheckServlet?userid="+userid) ; xmlHttp.onreadystatechange = checkUseridCallback ; xmlHttp.send(null) ; document.getElementById("msg").innerHTML = "正在验证..." ; } function checkUseridCallback(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ var text = xmlHttp.responseText ; if(text == "true"){ // 用户id已经存在了 document.getElementById("msg").innerHTML = "用户ID重复,无法使用!" ; flag = false ; } else { document.getElementById("msg").innerHTML = "此用户ID可以注册!" ; flag = true ; } } } } function checkForm(){ return flag ; } </script> </head> <body> <form action="regist.jsp" method="post" onsubmit="return checkForm()"> 用户ID:<input type="text" name="userid" onblur="checkUserid(this.value)"><span id="msg"></span><br> 姓 名:<input type="text" name="name"><br> 密 码:<input type="password" name="password"><br> <input type="submit" value="注册"> <input type="reset" value="重置"> </form> </body> </html>
web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Welcome to Tomcat</display-name> <description> Welcome to Tomcat </description> <servlet> <servlet-name>CheckServlet</servlet-name> <servlet-class>org.lxh.ajaxdemo.CheckServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckServlet</servlet-name> <url-pattern>/CheckServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
CheckServlet.java:
package org.lxh.ajaxdemo ; import java.sql.* ; import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* ; public class CheckServlet extends HttpServlet{ private static final long serialVersionUID = 1L; public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; public static final String DBURL = "jdbc:mysql://localhost:3306/mldn" ; public static final String DBUSER = "root" ; public static final String DBPASS = "linda0213" ; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ this.doPost(request,response) ; } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ request.setCharacterEncoding("GBK") ; response.setContentType("text/html") ; Connection conn = null ; PreparedStatement pstmt = null ; ResultSet rs = null ; PrintWriter out = response.getWriter() ; String userid = request.getParameter("userid") ; try{ Class.forName(DBDRIVER) ; conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ; String sql = "SELECT COUNT(userid) FROM user WHERE userid=?" ; System.out.println(sql); pstmt = conn.prepareStatement(sql) ; pstmt.setString(1,userid) ; rs = pstmt.executeQuery() ; if(rs.next()){ if(rs.getInt(1)>0){ // 用户ID已经存在了 out.print("true") ; } else { out.print("false") ; } } }catch(Exception e){ e.printStackTrace() ; }finally{ try{ conn.close() ; }catch(Exception e){} } } }
regist.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% 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>Regist OK</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> OK! <br> </body> </html>
AJAX分页:
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript"> var js = { XMLHttp:null, //发送请求函数 sendRequest:function(url,responseFun,callback){ //创建XMLHTTPRequest对象 (function(){ //根据浏览器类型创建XMLHTTPRequest对象 if(window.XMLHttpRequest){ js.XMLHttp = new XMLHttpRequest(); } else{ try{ js.XMLHttp = new ActionXObject("Msxml2.XMLHTTP"); }catch (e){ try{ js.XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e0){alert("Microsoft"+e0);} } } })(); //function end. js.XMLHttp.open("POST", url, true); js.XMLHttp.onreadystatechange = function(responseFunction){ if(js.XMLHttp.readyState == 4){ if(js.XMLHttp.status == 200){ responseFun(js.XMLHttp); }else{ document.getElementById("div").innerHTML = "<font color='red'>连接服务器异常...</font>" ; } } else{ //document.getElementById("div").innerHTML = "<font color='red'>数据加载中...</font>" ; } };//指定响应函数onreadystatechange js.XMLHttp.send(null); return js.XMLHttp; }//sendRequest:function }//js end //响应函数 function responseFunction(xmlhttp){ var xmlDOM = xmlhttp.responseXML; //接受服务器返回的xml文档 parse(xmlDOM);//解析XML文档 } //解析XML文档 function parse(xmlDOM){ var person = xmlDOM.getElementsByTagName("person"); var page = xmlDOM.getElementsByTagName("page")[0]; var currpage = page.getElementsByTagName("currpage")[0].firstChild.data; var pagecount = page.getElementsByTagName("pagecount")[0].firstChild.data; var prevpagehtml; var nextpagehtml; if((currpage-0)<=1){ prevpagehtml = "<a>上一页</a>"; }else{ prevpagehtml = "<a onclick='AjaxTest("+(currpage-1)+");' href='javascript:void(0);'>上一页</a>"; } if((currpage-0)<(pagecount-0)){ nextpagehtml = "<a onclick='AjaxTest("+(currpage-0+1)+");' href='javascript:void(0);'>下一页</a>"; }else{ nextpagehtml = "<a>下一页</a>"; } var html = "<table style='font-size: 12px; color: red'><tr><td width='80'>编号</td><td width='100'>姓名</td><td width='80'>年龄</td></tr>"; for(i=0;i<person.length;i++){ html = html+ "<tr><td>" +person[i].getElementsByTagName("pid")[0].firstChild.data+"</td><td>" +person[i].getElementsByTagName("pname")[0].firstChild.data+"</td><td>" +person[i].getElementsByTagName("age")[0].firstChild.data +"</td></tr>"; } html = html + "<tr ><td width='50'>"+prevpagehtml+"</td><td width='100'>共"+pagecount+"页 当前第"+currpage+"页</td><td width='80'>"+nextpagehtml+"</td></tr>"; html = html+"</table>"; document.getElementById("div").innerHTML=html; } //主调函数,以当前页作为参数 function AjaxTest(currpage) { js.sendRequest("AjaxServlet?currpage="+currpage,responseFunction,null); } </script> </head> <body onload="AjaxTest(1);"> <center> <div id="div"> </div> </center> </body> </html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description> This is the description of my J2EE component </description> <display-name> This is the display name of my J2EE component </display-name> <servlet-name>AjaxServlet</servlet-name> <servlet-class>AjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServlet</servlet-name> <url-pattern>/AjaxServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>CityServlet</servlet-name> <servlet-class>CityServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CityServlet</servlet-name> <url-pattern>/CityServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
page.java:
/** * @author QQ:373672872 * 分页Entity */ public class Page { //总记录数 private int total; //当前页 private int currpage; //每页显示记录数量 private int pagesize; //总页数 private int pagecount; //每页数据的开始下标 private int start; public Page(int total, int currpage, int pagesize) { this.setTotal(total); this.setCurrpage(currpage); this.setPagesize(pagesize); } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getCurrpage() { return currpage; } public void setCurrpage(int currpage) { this.currpage = currpage; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public int getPagecount() { //调用设置总页数方法 this.setPagecount(); return pagecount; } //设置总页数 public void setPagecount(){ this.pagecount = (total % pagesize == 0) ? total / pagesize : total / pagesize + 1; } public void setPagecount(int pagecount) { this.pagecount = pagecount; } public int getStart() { //调用设置行号方法 this.setStart(); return start; } //设置每页的起始行号 public void setStart(){ this.start = (this.getCurrpage()-1)*this.getPagesize(); } public void setStart(int start) { this.start = start; } }
AjaxServlet.java:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.*; /** * @author QQ:373672872 * @category 处理JSP页面提交的的异步查询请求,并以XML文件格式返回结果集 */ public class AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //当前页 int currpage = Integer.parseInt(request.getParameter("currpage")==null?"1":request.getParameter("currpage")); //总的记录数 int total = this.getResultCount(); //分页单位 int pagesize = 5; //Page类对象 Page page = new Page(total,currpage,pagesize); //用于返回给前台页面的XML文档 StringBuffer xmlDOM = new StringBuffer(); //调用查询方法 ResultSet rs = this.getResultSet(page.getStart(),page.getPagesize()); //添加XML根节点 xmlDOM.append("<root>"); try { //添加数据库查询出来的数据 xmlDOM.append("<persons>"); while (rs.next()) { xmlDOM.append("<person>"); xmlDOM.append("<pid>" + rs.getString("pid") + "</pid>"); xmlDOM.append("<pname>" + rs.getString("pname") + "</pname>"); xmlDOM.append("<age>" + rs.getString("age") + "</age>"); xmlDOM.append("</person>"); } rs.close(); xmlDOM.append("</persons>"); } catch (SQLException e) { System.out.println(e.getMessage()); } //添加分页信息 xmlDOM.append("<page>"); xmlDOM.append("<currpage>"+page.getCurrpage()+"</currpage>"); xmlDOM.append("<pagecount>"+page.getPagecount()+"</pagecount>"); xmlDOM.append("</page>"); xmlDOM.append("</root>"); //调用打印方法 this.print(request, response, xmlDOM.toString()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * @category 打印出XMLDOM文档,用于前台页面的接收 * @author QQ:373672872 * @param request * @param response * @param xmlDOM * @throws IOException */ private void print(HttpServletRequest request, HttpServletResponse response,String xmlDOM) throws IOException{ response.setCharacterEncoding("utf-8"); response.setContentType("text/xml"); PrintWriter out = response.getWriter(); out.print(xmlDOM); out.close(); } /** * @author QQ:373672872 * @category 返回当前页的查询结果 * @param 行号 * @param 长度 * @return ResultSet */ private ResultSet getResultSet(int start,int len){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = getConn(); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } catch (SQLException e) { System.out.println(e.getMessage()); } String sql = "select * from person order by pid limit ?,?"; //String sql = "select top "+len+" * from person where pid >= ? order by pid"; try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, start); pstmt.setInt(2, len); pstmt.setInt(1, start); rs = pstmt.executeQuery(); } catch (SQLException e) { System.out.println(e.getMessage()); } return rs; } /** * @author QQ:373672872 * @return 数据库中总的记录数 */ private int getResultCount(){ int count=0; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getConn(); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } catch (SQLException e) { System.out.println(e.getMessage()); } String sql = "select count(*) from person"; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException e) { System.out.println(e.getMessage()); } try { while(rs.next()){ count = rs.getInt(1); } stmt.close(); rs.close(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } return count; } /** * @author QQ:373672872 * @return 取得数据库连接驱动 * @throws ClassNotFoundException * @throws SQLException */ private Connection getConn() throws ClassNotFoundException, SQLException{ //String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String driver = "com.mysql.jdbc.Driver"; //String url = "jdbc:sqlserver://127.0.0.1:1433;database=persondb"; String url = "jdbc:mysql://localhost:3306/persondb"; String user = "root"; String password = "linda0213"; Class.forName(driver); return DriverManager.getConnection(url,user,password); } }
xml文件:
<root> <persons> <person> <pid>1</pid> <pname>BennyTan</pname> <age>20</age> </person> <person> <pid>2</pid> <pname>JayChou</pname> <age>23</age> </person> <person> <pid>3</pid> <pname>JolinTisa</pname> <age>28</age> </person> <person> <pid>4</pid> <pname>Jack</pname> <age>18</age> </person> <person> <pid>5</pid> <pname>Jolit</pname> <age>35</age> </person> </persons> <page> <currpage>1</currpage> <pagecount>5</pagecount> </page> </root>