Ajax技术就是页面的局部数据传输和局部刷新,减少了网页发送的数据量和网页生成的时间。Ajax分为两个部分,客户端部分和服务器端部分。
客户端部分:用js编写的程序,包括三个部分:1)发送数据到服务器;2)接收服务器的返回数据;3)局部刷新网页,显示服务器返回的的数据。
服务器端部分:处理来自客户端的数据并返回处理结果给客户端。
首先建立一个java web程序:
1.客户端部分,index.jsp:将用户姓名发送到服务器端。
<%@ page language="java" pageEncoding="GB2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<SCRIPT LANGUAGE="JavaScript">
var XMLHttpReq;
//创建XMLHttpRequest对象,通过XMLHttpRequest请求服务器端的数据
function createXMLHttpRequest() {
if(window.XMLHttpRequest) { //Mozilla 浏览器
XMLHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE浏览器
try {
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try {
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
//发送请求函数到服务器,这里服务器的处理程序为servlet程序
function sendRequest() {
document.getElementById("comments").innerHTML ="正在查询,请您稍等......";
createXMLHttpRequest();
var Pname=document.getElementById("Pname").value;
var url = "GetTime?name="+Pname;
XMLHttpReq.open("GET", url, true);
XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
XMLHttpReq.send(null); // 发送请求
}
//处理服务器端返回的信息函数
function processResponse() {
if (XMLHttpReq.readyState == 4) { // 判断对象状态
if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息
Display();
} else { //页面不正常
window.alert("您所请求的页面有异常。");
}
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<SCRIPT LANGUAGE="JavaScript">
var XMLHttpReq;
//创建XMLHttpRequest对象,通过XMLHttpRequest请求服务器端的数据
function createXMLHttpRequest() {
if(window.XMLHttpRequest) { //Mozilla 浏览器
XMLHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE浏览器
try {
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try {
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
//发送请求函数到服务器,这里服务器的处理程序为servlet程序
function sendRequest() {
document.getElementById("comments").innerHTML ="正在查询,请您稍等......";
createXMLHttpRequest();
var Pname=document.getElementById("Pname").value;
var url = "GetTime?name="+Pname;
XMLHttpReq.open("GET", url, true);
XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
XMLHttpReq.send(null); // 发送请求
}
//处理服务器端返回的信息函数
function processResponse() {
if (XMLHttpReq.readyState == 4) { // 判断对象状态
if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息
Display();
} else { //页面不正常
window.alert("您所请求的页面有异常。");
}
}
}
//网页局部刷新,显示服务器端返回的数据
function Display() {
var msg=XMLHttpReq.responseText;
document.getElementById('comments').value=msg;
}
</SCRIPT>
<body>
名称:<input type="text" value="" id="Pname" name="Pname" size="69">
<input type="submit" value="get time now" id=Submit1 name=Submit1
onClick="sendRequest()">
<TEXTAREA id="comments" name="comments" readonly rows=15 cols=76>
</TEXTAREA>
</body>
</html>
function Display() {
var msg=XMLHttpReq.responseText;
document.getElementById('comments').value=msg;
}
</SCRIPT>
<body>
名称:<input type="text" value="" id="Pname" name="Pname" size="69">
<input type="submit" value="get time now" id=Submit1 name=Submit1
onClick="sendRequest()">
<TEXTAREA id="comments" name="comments" readonly rows=15 cols=76>
</TEXTAREA>
</body>
</html>
2.服务器端部分,TimeServlet:接收客户端发送的姓名,并返回“姓名+当前的时间”。
package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TimeServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public TimeServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TimeServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public TimeServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
* 这里涉及到中文字符编码的问题,当字符在网络中传递时,不管对于这个字符是怎么编码的,java都认为它是iso8859编码。
* request.getParameter("name").getBytes("iso-8859-1"),"GBK"); 就是将iso8859编码下的字符串转换成GBK编码下的字符串。
* 然后通过new String()转换为java默认的编码中。
* 然后通过new String()转换为java默认的编码中。
*一句话,也就是解析客户端传来的中文字符串。
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Pname = new String(request.getParameter("name").getBytes("iso-8859-1"),"GBK");
Calendar c = Calendar.getInstance();
response.setContentType( "text/html;charset=GB2312 ");
PrintWriter out = response.getWriter();
out.println("Hello, "+Pname+". Now time is"+c.getTime().toString());
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Pname = new String(request.getParameter("name").getBytes("iso-8859-1"),"GBK");
Calendar c = Calendar.getInstance();
response.setContentType( "text/html;charset=GB2312 ");
PrintWriter out = response.getWriter();
out.println("Hello, "+Pname+". Now time is"+c.getTime().toString());
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
3.web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>TimeServlet</servlet-name>
<servlet-class>com.TimeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TimeServlet</servlet-name>
<url-pattern>/GetTime</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>TimeServlet</servlet-name>
<servlet-class>com.TimeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TimeServlet</servlet-name>
<url-pattern>/GetTime</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
这样子,一个java ajax的程序就写完了,客户端点击按钮,发送客户姓名到服务器端,服务器端的TimeServlet接收客户端姓名,并在后面附加上当前的时间,发送到客户端。客户端接收服务器端的信息,显示在页面的text中。例子中客户端向服务器端发送信息是通过get方式发送的
XMLHttpReq.open("GET", url, true);
XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
XMLHttpReq.send(null); // 发送请求
XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
XMLHttpReq.send(null); // 发送请求
也可以通过post方式发送,只需修改index.jsp文件中的sendRequest()函数:
function sendRequest()
{
document.getElementById("comments").innerHTML ="正在查询,请您稍等......";
createXMLHttpRequest();
var Pname=document.getElementById("Pname").value;
var url = "GetTime";
var param = "name="+Pname;
XMLHttpReq.open("post",url,true);
XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XMLHttpReq.onreadyStatechange= XMLHttpReq.onreadystatechange = processResponse;
XMLHttpReq.send(param);
}
document.getElementById("comments").innerHTML ="正在查询,请您稍等......";
createXMLHttpRequest();
var Pname=document.getElementById("Pname").value;
var url = "GetTime";
var param = "name="+Pname;
XMLHttpReq.open("post",url,true);
XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XMLHttpReq.onreadyStatechange= XMLHttpReq.onreadystatechange = processResponse;
XMLHttpReq.send(param);
}
服务器段部分,TimeServlet稍作修改,只需修改第一行,之所以这么修改是因为post和get方式提交中文数据是编码不同。
String Pname = new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");
关于中文编码的问题,可以参考
http://hi.baidu.com/twobrushes/blog/item/9928898f139808fe513d92c0.html