我的试验主要包括4种:
1.回传一个普通的String字符串.
2.回传一个组织好的Javascript字符串.
3.回传一个Json对象.(需要引入json.jar)
4.回传一个XML对象.
基本实现如下:
其中测试页面为:
001 | <%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> |
002 | <%request.setCharacterEncoding("UTF-8");%> |
003 | <html> |
004 | <head> |
005 | <title>测试Ajax页面</title> |
006 | </head> |
007 | <body> |
008 | <table width="100%" height="100%" > |
009 | <td align="center" valign="center" > |
010 | <form action="" method="post" onsubmit=""> |
011 | <table border="3" > |
012 | <tr> |
013 | <td> |
014 | <input name="试验返回String" type="button" value="试验返回String" onclick="testAjaxForString();" style="width:140px;"> |
015 | </td> |
016 | </tr> |
017 | <tr> |
018 | <td> |
019 | <input name="试验返回javascriptString" type="button" value="试验返回javascriptString" onclick="testAjaxForObject();" style="width:140px;"> |
020 | </td> |
021 | </tr> |
022 | <tr> |
023 | <td> |
024 | <input name="试验返回json" type="button" value="试验返回json" onclick="testAjaxForJson();" style="width:140px;"> |
025 | </td> |
026 | </tr> |
027 | <tr> |
028 | <td> |
029 | <input name="试验返回xml" type="button" value="试验返回xml" onclick="testAjaxForXml();" style="width:140px;"> |
030 | </td> |
031 | </tr> |
032 | </table> |
033 | </form> |
034 | </td> |
035 | </table> |
036 | </body> |
037 | </html> |
038 | |
039 | <script type="text/javascript"> |
040 | var xmlHttp ; |
041 | function createXmlHttpRequest(){ |
042 | if(window.ActiveXObject){ |
043 | xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") ; |
044 | }else if(window.XMLHttpRequest){ |
045 | xmlHttp = new XMLHttpRequest(); |
046 | } |
047 | } |
048 | /*返回String*/ |
049 | function testAjaxForString(){ |
050 | createXmlHttpRequest(); |
051 | var url = "HelloWorld?"; |
052 | var queryString = "name=songwei"; |
053 | url += queryString ; |
054 | // xmlHttp.onreadystatechange = parseHello ;//如果是异步,既open中最后一个参数为true.则打开该选项. |
055 | xmlHttp.open("post",url,false); |
056 | xmlHttp.send(null); |
057 | alert(xmlHttp.responseText); //如果是字符串或者xml. |
058 | } |
059 | |
060 | /*返回JsObject*/ |
061 | function testAjaxForObject(){ |
062 | createXmlHttpRequest(); |
063 | var url = "HelloWorldForObject?"; |
064 | var queryString = "name=songwei"; |
065 | url += queryString ; |
066 | // xmlHttp.onreadystatechange = parseHello ; |
067 | xmlHttp.open("post",false); |
068 | xmlHttp.send(null); |
069 | alert(xmlHttp.responseText); |
070 | var o = eval(xmlHttp.responseText); |
071 | alert("username="+o.username); |
072 | alert("password="+o.password); |
073 | var farray = o.friend ; |
074 | var fname =""; |
075 | for(var i=0;i<farray.length;i++){ |
076 | fname += farray[i]+" "; |
077 | } |
078 | alert("friend list ="+fname); |
079 | } |
080 | //返回Json |
081 | function testAjaxForJson(){ |
082 | createXmlHttpRequest(); |
083 | var url = "HelloWorldForJson?"; |
084 | var queryString = "name=songwei"; |
085 | url += queryString ; |
086 | xmlHttp.open("post",false); |
087 | xmlHttp.send(null); |
088 | alert(xmlHttp.responseText); |
089 | var o = eval("(" + xmlHttp.responseText + ")"); |
090 | alert(o.userInfo.username); |
091 | alert(o.userInfo.password); |
092 | alert(o.userInfo.friends[0]); |
093 | alert(o.userInfo.friends[1]); |
094 | } |
095 | |
096 | //返回XML |
097 | function testAjaxForXml(){ |
098 | createXmlHttpRequest(); |
099 | var url = "HelloWorldForXML?"; |
100 | var queryString = "name=songwei"; |
101 | url += queryString ; |
102 | xmlHttp.open("post",false); |
103 | xmlHttp.send(null); |
104 | alert(xmlHttp.responseXML); |
105 | alert ("tagName: " + xmlHttp.responseXML.documentElement.tagName); |
106 | var xmlDoc = xmlHttp.responseXML ; |
107 | var xmlRoot=xmlDoc.documentElement; |
108 | |
109 | var friendsItem=xmlRoot.getElementsByTagName("friends"); |
110 | alert(friendsItem[0].firstChild.firstChild.data); |
111 | alert(friendsItem[0].firstChild.nextSibling.firstChild.data); |
112 | var usernameItem = xmlRoot.getElementsByTagName("username"); |
113 | alert(usernameItem[0].firstChild.data); |
114 | |
115 | } |
116 | </script> |
对于各种回传方式的不同servlet实现:
1.普通字符串,HelloWorld.java(Servlet)
01 | public class HelloWorld extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { |
02 | public HelloWorld() { |
03 | super(); |
04 | } |
05 | protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { |
06 | doPost(request,response); |
07 | } |
08 | protected void doPost(HttpServletRequest request,IOException { |
09 | // TODO Auto-generated method stub |
10 | String name = request.getParameter("name"); |
11 | String str = "Hello "+name ; |
12 | PrintWriter pw = response.getWriter(); |
13 | pw.print(str); |
14 | pw.close(); |
15 | } |
16 | } |
2.Javascript字符串Servlet实现
HelloWorldForObject.java
01 | public class HelloWorldForObject extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { |
02 | public HelloWorldForObject() { |
03 | super(); |
04 | } |
05 | protected void doGet(HttpServletRequest request,response); |
07 | } |
08 | |
09 | protected void doPost(HttpServletRequest request,IOException { |
10 | String name = request.getParameter("name"); |
11 | User user = new User(); |
12 | user.setUsername(name); |
13 | user.setPassword("abc"); |
14 | List<String> friend = new ArrayList<String>(); |
15 | friend.add("wangdong"); |
16 | friend.add("zhaoyong"); |
17 | user.setFriend(friend); |
18 | StringBuffer sb = new StringBuffer(); |
19 | sb.append("var o = new Object();"); |
20 | sb.append("o.username ='"+user.getUsername()+"' ;"); |
21 | sb.append("o.password ='"+user.getPassword()+"' ;"); |
22 | sb.append("o.friend = new Array("); |
23 | String tmp = "" ; |
24 | for(String s : user.getFriend()){ |
25 | if(tmp.trim().length()<1){ |
26 | tmp += "'"+s+"'" ; |
27 | }else{ |
28 | tmp +="," ; |
29 | tmp += "'"+s+"'" ; |
30 | } |
31 | } |
32 | sb.append(tmp+") ;"); |
33 | sb.append("o;"); |
34 | PrintWriter pw = response.getWriter(); |
35 | pw.print(sb.toString()); |
36 | pw.close(); |
37 | } |
38 | } |
3.JSon对象实现
HelloWorldForJson.java
01 | public class HelloWorldForJson extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { |
02 | public HelloWorldForJson() { |
03 | super(); |
04 | } |
05 | protected void doGet(HttpServletRequest request,IOException { |
09 | response.setCharacterEncoding("UTF-8"); |
10 | response.setHeader("Cache-Control","no-cache"); |
11 | request.setCharacterEncoding("UTF-8"); |
12 | String result = new String(); |
13 | String name = request.getParameter("name"); |
14 | try{ |
15 | JSONObject jsonResult = new JSONObject(); |
16 | jsonResult.put("username",name); |
17 | jsonResult.put("password","password"); |
18 | JSONArray jsonFriends = new JSONArray(); |
19 | jsonFriends.put("张三"); |
20 | jsonFriends.put("李四"); |
21 | jsonResult.put("friends",jsonFriends); |
22 | result = new JSONObject().put("userInfo",jsonResult).toString(); |
23 | }catch(JSONException jex){ |
24 | jex.printStackTrace(); |
25 | } |
26 | response.getWriter().print(result); |
27 | response.getWriter().close(); |
28 | } |
29 | } |
4.XML对象实现
HelloWorldForXML.java
01 | public class HelloWorldForXML extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { |
02 | public HelloWorldForXML() { |
03 | super(); |
04 | } |
05 | protected void doGet(HttpServletRequest request,IOException { |
09 | String name = request.getParameter("name"); |
10 | Document doc = null ; |
11 | String docStr ="" ; |
12 | try{ |
13 | DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance(); |
14 | DocumentBuilder db = dbf.newDocumentBuilder(); |
15 | doc = db.newDocument(); |
16 | Element root = doc.createElement("userInfo"); |
17 | doc.appendChild(root); |
18 | Element nameE = doc.createElement("username"); |
19 | Text nameT = doc.createTextNode(name); |
20 | nameE.appendChild(nameT); |
21 | root.appendChild(nameE); |
22 | |
23 | Element passE = doc.createElement("password"); |
24 | Text passT = doc.createTextNode("password"); |
25 | passE.appendChild(passT); |
26 | root.appendChild(passE); |
27 | |
28 | Element friends = doc.createElement("friends"); |
29 | |
30 | Element friend1 = doc.createElement("friend"); |
31 | Text f1T = doc.createTextNode("张三"); |
32 | friend1.appendChild(f1T); |
33 | Element friend2 = doc.createElement("friend"); |
34 | Text f2T = doc.createTextNode("李四"); |
35 | friend2.appendChild(f2T); |
36 | |
37 | friends.appendChild(friend1); |
38 | friends.appendChild(friend2); |
39 | root.appendChild(friends); |
40 | |
41 | ByteArrayOutputStream bstream = null; |
42 | try { |
43 | bstream = new ByteArrayOutputStream(); |
44 | Transformer xformer = TransformerFactory.newInstance() |
45 | .newTransformer(); |
46 | Source source = new DOMSource(doc); |
47 | Result result = new StreamResult(bstream); |
48 | xformer.transform(source,result); |
49 | } catch (Exception e) { |
50 | e.printStackTrace(); |
51 | } |
52 | try { |
53 | docStr = new String(bstream.toByteArray(),"UTF-8"); |
54 | } catch (UnsupportedEncodingException e) { |
55 | e.printStackTrace(); |
56 | docStr = new String(bstream.toByteArray()); |
57 | } |
58 | System.out.println(docStr); |
59 | |
60 | }catch(ParserConfigurationException ex){ |
61 | ex.printStackTrace(); |
62 | } |
63 | response.setContentType("text/xml;charset=UTF-8"); |
64 | PrintWriter writer = response.getWriter(); |
65 | writer.print(docStr); |
66 | writer.flush(); |
67 | writer.close(); |
68 | } |
本文固定链接: http://anyoneking.com/archives/97 | 懒散狂徒的博客 原文链接:https://www.f2er.com/ajax/165549.html