分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

servlet与ajax数据交换(json格式)

发布时间:2023-09-06 01:50责任编辑:赖小花关键词:jsjson

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()},58 ????????????????????????function(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 ??????????});67 ?????????68 ???????})69 ????</script>70 </body>71 </html>

后端servlet部分(字符串拼接)

servlet部分@WebServlet("/AjaxTest")public class AjaxTest extends HttpServlet { ???private static final long serialVersionUID = 1L; ??????????/** ????* @see HttpServlet#HttpServlet() ????*/ ???public AjaxTest() { ???????super(); ???????// TODO Auto-generated constructor stub ???} ???/** ????* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) ????*/ ???protected void 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) ????*/ ???protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ???????// TODO Auto-generated method stub ???????doGet(request, response); ???}User类public class 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;}public void setUsername(String username) { ???this.username = username;}public String getSex() { ???return sex;}public void setSex(String sex) { ???this.sex = sex;}public String getAge() { ???return age;}public void setAge(String age) { ???this.age = age;}public String getPhone() { ???return phone;}public void setPhone(String phone) { ???this.phone = phone;}@Overridepublic String toString() { ???return "{" + ?"\"username\"" + ‘:‘ + "\""+ username +"\"" + ","+ "\"sex\""+‘:‘ +"\"" +sex +"\""+‘,‘+ "\"age\""+‘:‘ + "\"" + age + "\"" +‘,‘+"\"phone\""+‘:‘ + "\""+phone+"\"" + "}";}}
View Code

具体实例代码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()},22 ?????????????????function(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 ????????????});31 ???????????32 ???????})33 ??</script>34 </body>35 </html>
View Code

servlet部分(调用gson方法)

servlet部分@WebServlet("/ajax")public class ajax extends HttpServlet { ???private static final long serialVersionUID = 1L; ??????????/** ????* @see HttpServlet#HttpServlet() ????*/ ???public ajax() { ???????super(); ???????// TODO Auto-generated constructor stub ???} ???/** ????* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) ????*/ ???protected void 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) ????*/ ???protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ???????// TODO Auto-generated method stub ???????doGet(request, response); ???}}User类部分public class User { ?private String name; ?private String sex; ?private int age;public User(String name, String sex, int age) { ???this.name = name; ???this.sex = sex; ???this.age = age;}public String getName() { ???return name;}public void setName(String name) { ???this.name = name;}public String getSex() { ???return sex;}public void setSex(String sex) { ???this.sex = sex;}public int getAge() { ???return age;}public void setAge(int age) { ???this.age = age;} ?}
View Code

具体实例代码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">12 13 </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()},20 ?????????????????function(data,textStatus){21 ??????????????????????console.log(data); 22 ??????????????????????for(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 ????????????});33 ???????????34 ???????})35 ??</script>36 </body>37 </html>

servlet部分(调用gson方法处理数据)

 1 servlet部分 2 @WebServlet("/ajax") 3 public class ajax extends HttpServlet { 4 ????private static final long serialVersionUID = 1L; 5 ????????6 ????/** 7 ?????* @see HttpServlet#HttpServlet() 8 ?????*/ 9 ????public ajax() {10 ????????super();11 ????????// TODO Auto-generated constructor stub12 ????}13 ????/**14 ?????* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)15 ?????*/16 ????protected void 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);28 ????????29 ????????String result = gson.toJson(list); ???30 ????????response.getWriter().append(result);31 ????}32 ????/**33 ?????* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)34 ?????*/35 ????protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {36 ????????// TODO Auto-generated method stub37 ????????doGet(request, response);38 ????}39 40 }41 42 User类43 44 45 public class User {46 ??private String name;47 ??private String sex;48 ??private int age;49 public User(String name, String sex, int age) {50 ????this.name = name;51 ????this.sex = sex;52 ????this.age = age;53 }54 public String getName() {55 ????return name;56 }57 public void setName(String name) {58 ????this.name = name;59 }60 public String getSex() {61 ????return sex;62 }63 public void setSex(String sex) {64 ????this.sex = sex;65 }66 public int getAge() {67 ????return age;68 }69 public void setAge(int age) {70 ????this.age = age;71 }72 ??73 }
View Code

servlet与ajax数据交换(json格式)

原文地址:https://www.cnblogs.com/TheGCC/p/8891251.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved