本方法不借助于任何的框架及开源项目,体现AJAX在J2EE中的实现如下功能,由页面向服务器发出请求,返回一个字符串,客户端页面显示该字符串。
1.1 Servlet
响应客户端请求的Servlet类为一普通的Servlet,关键在于使用了ServletOutputStream控制输出流,该输出即可则客户端获取。代码如下所示:
package
lld.test.ajax;
import
java.io.IOException;
import
javax.servlet.ServletException;
import
javax.servlet.ServletOutputStream;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
public
class
SimpleAjaxServlet
extends
HttpServlet
...
{
private static final long serialVersionUID = -668635463669389981L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
...{
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
...{
String uname = req.getParameter("uname");
ServletOutputStream os = resp.getOutputStream();
os.print("Hello, " + uname);
System.out.println("Hello, AJAX!");
}
}
如果客户端传入参数 uname=London,则该Servlet将字符串“Hello, London”输出至客户端。
1.2 JSP
在JSP中使用如下HTML代码发送请求
<input type="button" value="Simple" onclick="simple_ajax()" />
关键在于JavaScript代码的写法,如下所示:
var
bXmlHttpSupport
=
(
typeof
XMLHttpRequest
!=
"
undefined
"
||
window.ActiveXObject);
function
GetXMLHttpRequest()
...
{
var oRequest;
if(window.ActiveXObject)
...{
var arrSignatures = ["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for (var i=0; i < arrSignatures.length; i++) ...{
try ...{
oRequest = new ActiveXObject(arrSignatures[i]);
return oRequest;
} catch (oError) ...{ /**//*ignore*/ }
}
}
else if(window.XMLHttpRequest)
...{
oRequest = new XMLHttpRequest();
return oRequest;
}
throw new Error("MSXML is not installed on your system.");
}
function
simple_ajax()
...
{
if(bXmlHttpSupport)
...{
var frm = document.form1;
var sUrl = "SimpleAjax.do?uname=London";
var oRequest = GetXMLHttpRequest();
oRequest.onreadystatechange = function()
...{
if(oRequest.readyState == 4)
...{
alert(oRequest.responseText);
}
};
oRequest.open('POST', sUrl);
oRequest.send(null);
}
}
其中的XMLHttpRequest用于获取发送异步XML请求的ActiveX对象,可作为一个通用函数在项目中使用。
在simple_ajax函数中,关键在于定义XMLHttpRequest.onReadyStateChange事件,指定请求返回后的动作,在此我只是简单地显示从服务器返回的结果。
该程序在IE和Firefox下均测试通过, 如果谁想要源程序, 可给我发邮件