我的试验主要包括4种:
1.回传一个普通的String字符串.
2.回传一个组织好的Javascript字符串.
3.回传一个Json对象.(需要引入json.jar)
4.回传一个XML对象.
基本实现如下:
其中测试页面为:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<title>测试Ajax页面</title>
</head>
<body>
<table width="100%" height="100%" >
<td align="center" valign="center" >
<form action="" method="post" onsubmit="">
<table border="3" >
<tr>
<td>
<input name="试验返回String" type="button" value="试验返回String" onclick="testAjaxForString();" style="width:140px;">
</td>
</tr>
<tr>
<td>
<input name="试验返回javascriptString" type="button" value="试验返回javascriptString" onclick="testAjaxForObject();" style="width:140px;">
</td>
</tr>
<tr>
<td>
<input name="试验返回json" type="button" value="试验返回json" onclick="testAjaxForJson();" style="width:140px;">
</td>
</tr>
<tr>
<td>
<input name="试验返回xml" type="button" value="试验返回xml" onclick="testAjaxForXml();" style="width:140px;">
</td>
</tr>
</table>
</form>
</td>
</table>
</body>
</html>
<script type="text/javascript">
var xmlHttp ;
function createXmlHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") ;
}else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
/**//**//**//*返回String*/
function testAjaxForString(){
createXmlHttpRequest();
var url = "HelloWorld?";
var queryString = "name=songwei";
url += queryString ;
// xmlHttp.onreadystatechange = parseHello ;//如果是异步,既open中最后一个参数为true.则打开该选项.
xmlHttp.open("post",url,false);
xmlHttp.send(null);
alert(xmlHttp.responseText); //如果是字符串或者xml.
}
/**//**//**//*返回JsObject*/
function testAjaxForObject(){
createXmlHttpRequest();
var url = "HelloWorldForObject?";
var queryString = "name=songwei";
url += queryString ;
// xmlHttp.onreadystatechange = parseHello ;
xmlHttp.open("post",url,false);
xmlHttp.send(null);
alert(xmlHttp.responseText);
var o = eval(xmlHttp.responseText);
alert("username="+o.username);
alert("password="+o.password);
var farray = o.friend ;
var fname ="";
for(var i=0;i<farray.length;i++){
fname += farray[i]+" ";
}
alert("friend list ="+fname);
}
//返回Json
function testAjaxForJson(){
createXmlHttpRequest();
var url = "HelloWorldForJson?";
var queryString = "name=songwei";
url += queryString ;
xmlHttp.open("post",url,false);
xmlHttp.send(null);
alert(xmlHttp.responseText);
var o = eval("(" + xmlHttp.responseText + ")");
alert(o.userInfo.username);
alert(o.userInfo.password);
alert(o.userInfo.friends[0]);
alert(o.userInfo.friends[1]);
}
//返回XML
function testAjaxForXml(){
createXmlHttpRequest();
var url = "HelloWorldForXML?";
var queryString = "name=songwei";
url += queryString ;
xmlHttp.open("post",url,false);
xmlHttp.send(null);
alert(xmlHttp.responseXML);
alert ("tagName: " + xmlHttp.responseXML.documentElement.tagName);
var xmlDoc = xmlHttp.responseXML ;
var xmlRoot=xmlDoc.documentElement;
var friendsItem=xmlRoot.getElementsByTagName("friends");
alert(friendsItem[0].firstChild.firstChild.data);
alert(friendsItem[0].firstChild.nextSibling.firstChild.data);
var usernameItem = xmlRoot.getElementsByTagName("username");
alert(usernameItem[0].firstChild.data);
}
</script>对于各种回传方式的不同servlet实现:
1.普通字符串 ,HelloWorld.java(Servlet)
public class HelloWorld extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public HelloWorld() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String str = "Hello "+name ;
PrintWriter pw = response.getWriter();
pw.print(str);
pw.close();
}
}
2.Javascript字符串Servlet实现
HelloWorldForObject.java
public class HelloWorldForObject extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public HelloWorldForObject() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
User user = new User();
user.setUsername(name);
user.setPassword("abc");
List<String> friend = new ArrayList<String>();
friend.add("wangdong");
friend.add("zhaoyong");
user.setFriend(friend);
StringBuffer sb = new StringBuffer();
sb.append("var o = new Object();");
sb.append("o.username ='"+user.getUsername()+"' ;");
sb.append("o.password ='"+user.getPassword()+"' ;");
sb.append("o.friend = new Array(");
String tmp = "" ;
for(String s : user.getFriend()){
if(tmp.trim().length()<1){
tmp += "'"+s+"'" ;
}else{
tmp +="," ;
tmp += "'"+s+"'" ;
}
}
sb.append(tmp+") ;");
sb.append("o;");
PrintWriter pw = response.getWriter();
pw.print(sb.toString());
pw.close();
}
}
3.JSon对象实现
HelloWorldForJson.java
public class HelloWorldForJson extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public HelloWorldForJson() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control","no-cache");
request.setCharacterEncoding("UTF-8");
String result = new String();
String name = request.getParameter("name");
try{
JSONObject jsonResult = new JSONObject();
jsonResult.put("username",name);
jsonResult.put("password","password");
JSONArray jsonFriends = new JSONArray();
jsonFriends.put("张三");
jsonFriends.put("李四");
jsonResult.put("friends",jsonFriends);
result = new JSONObject().put("userInfo", jsonResult).toString();
}catch(JSONException jex){
jex.printStackTrace();
}
response.getWriter().print(result);
response.getWriter().close();
}
}
4.XML对象实现
HelloWorldForXML.java
public class HelloWorldForXML extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public HelloWorldForXML() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
Document doc = null ;
String docStr ="" ;
try{
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
Element root = doc.createElement("userInfo");
doc.appendChild(root);
Element nameE = doc.createElement("username");
Text nameT = doc.createTextNode(name);
nameE.appendChild(nameT);
root.appendChild(nameE);
Element passE = doc.createElement("password");
Text passT = doc.createTextNode("password");
passE.appendChild(passT);
root.appendChild(passE);
Element friends = doc.createElement("friends");
Element friend1 = doc.createElement("friend");
Text f1T = doc.createTextNode("张三");
friend1.appendChild(f1T);
Element friend2 = doc.createElement("friend");
Text f2T = doc.createTextNode("李四");
friend2.appendChild(f2T);
friends.appendChild(friend1);
friends.appendChild(friend2);
root.appendChild(friends);
ByteArrayOutputStream bstream = null;
try {
bstream = new ByteArrayOutputStream();
Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
Source source = new DOMSource(doc);
Result result = new StreamResult(bstream);
xformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
try {
docStr = new String(bstream.toByteArray(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
docStr = new String(bstream.toByteArray());
}
System.out.println(docStr);
}catch(ParserConfigurationException ex){
ex.printStackTrace();
}
response.setContentType("text/xml;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.print(docStr);
writer.flush();
writer.close();
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/anyoneking/archive/2008/05/23/2472145.aspx