servlet与ajax数据交换(json格式)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了servlet与ajax数据交换(json格式),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含10753字,纯文字阅读大概需要16分钟。
内容图文
JSON数据格式:
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
(1)“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
(2)值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
JSON具体的表现形式:
(1)对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。
例:{“name”:“zhangsan”} //单属性 或者多个属性 {“name”:“lisi”,“sex”:“男” } // 具体对象
(2)数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。
例: ["value1","value2","value3"] //数组形式 [{“name”:“zhangsan1”},{“name”:“zhangsan2”},{“name”:“zhangsan3”}] //对象数组
Servlet与前端ajax的数据交互:
主要流程为 前端获取数据通过ajax的异步传输传至servlet,servlet处理数据后,通过response回传至前端页面。
注意: 一般在传输过程中会遇到两个比较常见的问题,第一就是传回前端时乱码问题,这个问题可以通过 在servlet处理方法中加入:response.setCharacterEncoding("UTF-8")解决;第二就是传至前端后,不会触发ajax中的回调函数,原因是因为servlet传回的json数据格式不合法而没有触发ajax的success状态。
关于servlet返回的json数据处理方法:
(1)自己拼接json字符串(出错率较高),使其数据满足json格式
JSON对于servlet处理格式要求,键必须加双引号,值分为字符串和数字,数字可不加引号,字符串必须加引号
例: {“"name":"zhansan", "age":13, "sex":"男" } // 这种为标准格式,字符串类型加引号,纯数字可不加
将一个独立对象转为以上的格式的字符串形式,才可以通过response.getWrite.append()传至前端 ajax 中,成功处罚回调函数
String result = "{"+"/"name/""+":"+"/""+name+"/""+","+"/"age/""+":"+"/""+age+"/""+","+"/"sex/""+":"+"/""+sex+"/""+"}";
(2)调用第三方封装好的 json 数据转换方法(个人使用的是Gson,链接地址:https://pan.baidu.com/s/1Yu91BYlqoJSXpzk37ZXZ6g)
建议使用这种方法,高效,简洁,适用于各种数据集合(list,map等)。详细使用可看下列实例(具体代码1)。
具体实例代码1(采用第一种字符串拼接方式)
前端html部分(含ajax)
1 < html > 2 < head > 3 < meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" > 4 < title >Insert title here</title> 5<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> 6</head> 7<body> 8<div class="box"> 9<table>10<tr>11<td>姓名</td>12<td><input name="username" type="text"></td>13</tr>14<tr>15<td>性别</td>16<td><input name="sex" type="text"></td>17</tr>18<tr>19<td>年龄</td>20<td><input name="age" type="text"></td>21</tr>22<tr>23<td>手机号</td>24<td><input name="phone" type="text"></td>25</tr>26<tr><td><button>提交</button></td></tr>27</table>28</div>29<div>30<table>31 信息返回 32<tr>33<td>姓名</td>34<td id="name"></td>35</tr>36<tr>37<td>性别</td>38<td id="sex"></td>39</tr>40<tr>41<td>年龄</td>42<td id="age"></td>43</tr>44<tr>45<td>手机号</td>46<td id="phone"></td>47</tr>48</table>49</div>50<script>51 $(function(){ 52 $("button").click(function(){ 53 $.post("AjaxTest", 54 {‘username‘:$("input[name=username]").val(), 55‘sex‘:$("input[name=sex]").val(), 56‘age‘:$("input[name=age]").val(), 57‘phone‘:$("input[name=phone]").val()}, 58function(data,textStatus){ 59 console.log(textStatus); 60 console.log(data.username); 61 $("#name").html(data.username); 62 $("#sex").html(data.sex); 63 $("#age").html(data.age); 64 $("#phone").html(data.phone); 65 },"json"); 66 }); 6768 }) 69</script>70</body>71</html>
后端servlet部分(字符串拼接)
servlet部分 @WebServlet("/AjaxTest") publicclass AjaxTest extends HttpServlet { privatestaticfinallong serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */public AjaxTest() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String name = request.getParameter("username"); String sex = request.getParameter("sex"); String age = request.getParameter("age"); String phone = request.getParameter("phone"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); User one = new User(name,sex,age,phone); String result = one.toString(); System.out.println(result); response.getWriter().append(result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } User类 publicclass User { private String username; private String sex; private String age; private String phone; public User(String username, String sex, String age, String phone) { this.username = username; this.sex = sex; this.age = age; this.phone = phone; } public String getUsername() { return username; } publicvoid setUsername(String username) { this.username = username; } public String getSex() { return sex; } publicvoid setSex(String sex) { this.sex = sex; } public String getAge() { return age; } publicvoid setAge(String age) { this.age = age; } public String getPhone() { return phone; } publicvoid setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "{" + "\"username\"" + ‘:‘ + "\""+ username +"\"" + ","+ "\"sex\""+‘:‘ +"\"" +sex +"\""+‘,‘+ "\"age\""+‘:‘ + "\"" + age + "\"" +‘,‘+"\"phone\""+‘:‘ + "\""+phone+"\"" + "}"; } }
具体实例代码2(采用gson转换json方式处理)
前端代码(含ajax)
1 < html > 2 < head > 3 4 < meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" > 5 < title >Insert title here</title> 6<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> 7</head> 8<body> 9<input type="text" name="cc" / >10<input type="submit"/>11<div>12 姓名:<span id="name"></span><br/>13 性别:<span id="sex"></span><br/>14 年龄: <span id="age"></span>15</div>16</form>17<script type="text/javascript">18 $(function(){ 19 $("input[type=submit]").click(function(){ 20 $.post("ajax", 21 {"cc":$("input[name=cc]").val()}, 22function(data,textStatus){ 23 console.log(data.name); 24 $("#name").html(data.name); 25 $("#sex").html(data.sex); 26 $("#age").html(data.age); 27 }, 28"json"29 ); 30 }); 3132 }) 33</script>34</body>35</html>
servlet部分(调用gson方法)
servlet部分 @WebServlet("/ajax") publicclass ajax extends HttpServlet { privatestaticfinallong serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */public ajax() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); String c = request.getParameter("cc"); System.out.println(c); User one = new User(c, "男", 13); Gson gson = new Gson(); String result = gson.toJson(one); response.getWriter().append(result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } User类部分 publicclass User { private String name; private String sex; privateint age; public User(String name, String sex, int age) { this.name = name; this.sex = sex; this.age = age; } public String getName() { return name; } publicvoid setName(String name) { this.name = name; } public String getSex() { return sex; } publicvoid setSex(String sex) { this.sex = sex; } publicint getAge() { return age; } publicvoid setAge(int age) { this.age = age; } }
具体实例代码3(多组数据传至ajax)
前端代码(含ajax)
1 < html > 2 < head > 3 4 < meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" > 5 < title >Insert title here</title> 6<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> 7</head> 8<body> 9<input type="text" name="ceshi">10<input type="submit" value="获取名单"/>11<table id="table">1213</table>14</form>15<script type="text/javascript">16 $(function(){ 17 $("input[type=submit]").click(function(){ 18 $.post("ajax", 19 {"ceshi":$("input[name=ceshi]").val()}, 20function(data,textStatus){ 21 console.log(data); 22for(var i =0;i<data.length; i++) 23 { 24 $("#table").append( $("<tr></tr>") 25 .append($("<td></td>").html(data[i].name)) 26 .append($("<td></td>").html(data[i].sex)) 27 .append($("<td></td>").html(data[i].age))); 28 } 29 }, 30"json"31 ); 32 }); 3334 }) 35</script>36</body>37</html>
servlet部分(调用gson方法处理数据)
1 servlet部分 2 @WebServlet("/ajax") 3publicclass ajax extends HttpServlet { 4privatestaticfinallong serialVersionUID = 1L; 5 6/** 7 * @see HttpServlet#HttpServlet() 8*/ 9public ajax() { 10super(); 11// TODO Auto-generated constructor stub12 } 13/**14 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 15*/16protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17// TODO Auto-generated method stub18 response.setCharacterEncoding("utf-8"); 19 String string = request.getParameter("ceshi"); 20 Gson gson = new Gson(); 21 List list = new ArrayList(); 22 User one = new User("张三", "男", 13); 23 User two = new User("李四","男", 15); 24 User three = new User("王五","男", 20); 25 list.add(one); 26 list.add(two); 27 list.add(three); 2829 String result = gson.toJson(list); 30 response.getWriter().append(result); 31 } 32/**33 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 34*/35protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 36// TODO Auto-generated method stub37 doGet(request, response); 38 } 3940} 4142User类 434445publicclass User { 46private String name; 47private String sex; 48privateint age; 49public User(String name, String sex, int age) { 50this.name = name; 51this.sex = sex; 52this.age = age; 53} 54public String getName() { 55return name; 56} 57publicvoid setName(String name) { 58this.name = name; 59} 60public String getSex() { 61return sex; 62} 63publicvoid setSex(String sex) { 64this.sex = sex; 65} 66publicint getAge() { 67return age; 68} 69publicvoid setAge(int age) { 70this.age = age; 71} 7273 }
原文:https://www.cnblogs.com/TheGCC/p/8891251.html
内容总结
以上是互联网集市为您收集整理的servlet与ajax数据交换(json格式)全部内容,希望文章能够帮你解决servlet与ajax数据交换(json格式)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。