JavaWeb-2 Ajax以JSON格式访问Servlet

1.客户端代码

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Bootstrap 实例 - 水平表单</title>
 6     <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">  
 7     <link rel="stylesheet" type="text/css" href="./fonts/iconfont.css">
 8     <script src="./js/jquery.min.js"></script>
 9     <script src="./js/bootstrap.min.js"></script>
10 </head>
11 <body>
12 
13 <form class="form-horizontal" role="form">
14     <div class="form-group">
15         <label for="firstname" class="col-sm-2 control-label">城市</label>
16         <div class="col-sm-10">
17             <input type="text" class="form-control" id="firstname" 
18                    placeholder="请输入城市">
19         </div>
20     </div>
21     <div class="form-group">
22         <label for="lastname" class="col-sm-2 control-label">邮编</label>
23         <div class="col-sm-10">
24             <input type="text" class="form-control" id="lastname" 
25                    placeholder="请输入邮编">
26         </div>
27     </div>
28     <div class="form-group">
29         <div class="col-sm-offset-2 col-sm-10">
30             <div class="checkbox">
31                 <label>
32                     <input type="checkbox"> 请记住我
33                 </label>
34             </div>
35         </div>
36     </div>
37     <div class="form-group">
38         <div class="col-sm-offset-2 col-sm-10">
39             <button type="submit" class="btn btn-default" onclick="onSubmit()">提交</button>
40         </div>
41     </div>
42 </form>
43 
44 </body>
45 <script type="text/javascript">
46     function onSubmit() {
47         alert("调用AJAX开始向服务器发送请求!");
48         //document.getElementById("findBtn").value = "稍等";
49 
50         //获取输入框的值
51         var val_first = document.getElementById("firstname").value;
52         var val_last = document.getElementById("lastname").value;
53         var url = "/dynwp03/CityInfoWeb";
54         url = encodeURI(url, "UTF-8");//编码为UTF-8
55 
56         if (window.XMLHttpRequest) { // IE7及以上, Firefox, Opera支持
57             xhr = new XMLHttpRequest();
58         } else if (window.ActiveXObject) { // IE5,IE6支持
59             xhr = new ActiveXObject("Microsoft.XMLHTTP");
60         }
61         if (xhr) {
62             
63             var data = {
64                     firstname: val_first,
65                     lastname: val_last
66                 };
67             var jsonData = JSON.stringify(data);
68             
69             xhr.onreadystatechange = onCompleted;
70             xhr.open("POST", url, true);
71             //xhr.setRequestHeader('If-Modified-Since', '0');//清除缓存
72             xhr.setRequestHeader("Content-Type","application/json");
73             
74             xhr.send(jsonData);
75             
76         }
77         function  onCompleted(){
78             if (xhr.readyState === 4 && xhr.status === 200) {
79                   // 请求成功,处理返回的数据
80                   var responset = JSON.parse(xhr.responseText);
81                   alert(xhr.responseText);
82                   //console.log(response);
83                 }
84             };
85     }
86 </script>
87 </html>

这里需要注意将onCompleted方法单独领出来写。

2. Servlet服务代码

 1 package dynwp;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStreamReader;
 5 import java.io.PrintWriter;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import com.alibaba.fastjson.JSON;
13 import com.alibaba.fastjson.JSONObject;
14 
15 import javax.servlet.ServletInputStream;
16 import dynwp.AxCity;
17 /**
18  * Servlet implementation class CityInfoWeb
19  */
20 public class CityInfoWeb extends HttpServlet {
21     private static final long serialVersionUID = 1L;
22 
23     /**
24      * Default constructor. 
25      */
26     public CityInfoWeb() {
27         // TODO Auto-generated constructor stub
28     }
29 
30     /**
31      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
32      */
33     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
34         // TODO Auto-generated method stub
35         //response.getWriter().append("Served at: ").append(request.getContextPath());
36         response.setHeader("CacheControl", "nocache");
37         response.setCharacterEncoding("UTF-8");
38         AxCity city=new AxCity();
39         city.setId(1);
40         city.setName("北京");
41         city.setDescribe("北京是中华人民共和国的首都,是全国的政治和文化中心。");
42         String jsonString = JSON.toJSONString(city);
43         response.setContentType("application/json");
44         PrintWriter out = response.getWriter();
45         out.append(jsonString);
46     }
47 
48     /**
49      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
50      */
51     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
52         // TODO Auto-generated method stub
53         InputStreamReader insr = new InputStreamReader(request.getInputStream(),"utf-8");
54         String result = "";
55         int respInt = insr.read();
56         while(respInt!=-1) {
57             result +=(char)respInt;
58             respInt = insr.read();
59         }
60         JSONObject jsonRet = JSONObject.parseObject(result);
61         System.out.println(jsonRet.getString("firstname"));
62         System.out.println(jsonRet.getString("lastname"));
63 
64         response.setHeader("CacheControl", "nocache");
65         response.setCharacterEncoding("UTF-8");
66         //response.setStatus(200);
67         PrintWriter out = response.getWriter();
68 //        out.append(jsonRet.getString("firstname"));
69 //        out.append(jsonRet.getString("lastname"));
70         AxCity city=new AxCity();
71         city.setId(10010);
72         city.setName(jsonRet.getString("firstname"));
73         city.setDescribe("北京是中华人民共和国的首都,是全国的政治和文化中心。");
74         String jsonString = JSON.toJSONString(city);
75         response.setContentType("application/json");
76         out.write(jsonString);
77         out.flush();
78         out.close();
79     }
80 
81 }

 3.结果

 

posted @ 2024-12-16 20:29  太一吾鱼水  阅读(7)  评论(0编辑  收藏  举报