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

时间:2023-12-15 20:06:14

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)

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div class="box">
<table>
<tr>
<td>姓名</td>
<td><input name="username" type="text"></td>
</tr>
<tr>
<td>性别</td>
<td><input name="sex" type="text"></td>
</tr>
<tr>
<td>年龄</td>
<td><input name="age" type="text"></td>
</tr>
<tr>
<td>手机号</td>
<td><input name="phone" type="text"></td>
</tr>
<tr><td><button>提交</button></td></tr>
</table>
</div>
<div>
<table>
信息返回
<tr>
<td>姓名</td>
<td id="name"></td>
</tr>
<tr>
<td>性别</td>
<td id="sex"></td>
</tr>
<tr>
<td>年龄</td>
<td id="age"></td>
</tr>
<tr>
<td>手机号</td>
<td id="phone"></td>
</tr>
</table>
</div>
<script>
$(function(){
$("button").click(function(){
$.post("AjaxTest",
{'username':$("input[name=username]").val(),
'sex':$("input[name=sex]").val(),
'age':$("input[name=age]").val(),
'phone':$("input[name=phone]").val()},
function(data,textStatus){
console.log(textStatus);
console.log(data.username);
$("#name").html(data.username);
$("#sex").html(data.sex);
$("#age").html(data.age);
$("#phone").html(data.phone);
},"json");
}); })
</script>
</body>
</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;
} @Override
public String toString() {
return "{" + "\"username\"" + ':' + "\""+ username +"\"" + ","+ "\"sex\""+':' +"\"" +sex +"\""+','+ "\"age\""+':' + "\"" + age + "\"" +','+"\"phone\""+':' + "\""+phone+"\"" + "}";
}
}

具体实例代码2(采用gson转换json方式处理)

前端代码(含ajax)

 <html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<input type="text" name="cc" / >
<input type="submit" />
<div>
姓名:<span id="name"></span> <br/>
性别:<span id="sex"></span><br/>
年龄: <span id="age"></span>
</div>
</form>
<script type="text/javascript">
$(function(){
$("input[type=submit]").click(function(){
$.post("ajax",
{"cc":$("input[name=cc]").val()},
function(data,textStatus){
console.log(data.name);
$("#name").html(data.name);
$("#sex").html(data.sex);
$("#age").html(data.age);
},
"json"
);
}); })
</script>
</body>
</html>

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;
} }

具体实例代码3(多组数据传至ajax)

前端代码(含ajax)

 <html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<input type="text" name="ceshi">
<input type="submit" value="获取名单"/>
<table id="table"> </table>
</form>
<script type="text/javascript">
$(function(){
$("input[type=submit]").click(function(){
$.post("ajax",
{"ceshi":$("input[name=ceshi]").val()},
function(data,textStatus){
console.log(data);
for(var i = 0;i<data.length; i++)
{
$("#table").append( $("<tr></tr>")
.append($("<td></td>").html(data[i].name))
.append($("<td></td>").html(data[i].sex))
.append($("<td></td>").html(data[i].age)));
}
},
"json"
);
}); })
</script>
</body>
</html>

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 string = request.getParameter("ceshi");
Gson gson = new Gson();
List list = new ArrayList();
User one = new User("张三", "男", 13);
User two = new User("李四","男", 15);
User three = new User("王五","男", 20);
list.add(one);
list.add(two);
list.add(three); String result = gson.toJson(list);
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;
} }