servlet中将值以json格式传入
详细连接https://blog.csdn.net/e_wsq/article/details/71038270
$('#but_json_json').click(function(){ var j ={"name":"王","password":123456}; $.ajax( { url:"servlet/JsonObject", //访问路径 type:"POST", //访问方式 data:j, //传入服务端的数据 dataType:"json", contentType:"application/json;charset=utf-8", success : function(data){ alert(data); alert(data.name); alert(data.password); } } ); }); Servlet: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user = request.getParameter("j"); String name = request.getParameter("name"); String password = request.getParameter("password"); System.out.println(user); //JSON对象 JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("password", password).accumulate("name", "www"); response.setContentType("application/json"); response.getWriter().write(jsonObject.toString());
现在的问题是,我可以从客户端将Servlet中传出的数据解析,如上面的name=www,但客户端传入的对象
(var j ={"name":"王","password":123456})在Servlet中取不到,好像是说要先去对象,我觉得应该是,
毕竟json提供了很多方法将取到到的json数据转换为别的格式,但还是搞不懂。本人新手,第一次接触,希望知道的朋友指定一下,感激不尽!
答:
我是这样理解的 首先 对你要传递 给 服务器(servlet)的 json序列化 用JSON.stringify,
确保我们传递的字符串 符合 json 结构 ,由于我们传递的数据 是以流的形式 传递到服务器,所以我们应该在
服务器端 读进缓冲区 在转换字符串输出
public String readJSONString(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
return json.toString();
}
} 之后 再转成 jsonObject 对象。就可以取到值了
还有一点 要注意 编码格式
=============================================================
详细连接 https://www.cnblogs.com/TheGCC/p/8891251.html
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> <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; } }