后台|服务器和客户端json数据传输

例如客户端通过ajax发送json请求数据

$.ajax({ type:"get", url:"${ctxPath}/login", contentType:"application/json,charset=UTF-8", data:{ "handle":"login", "name":"张三" }, dataType:'json', success: function(data){ console.log(data); }, error: function(){ console.log("请求数据失败"); }

【后台|服务器和客户端json数据传输】服务器端取查询数据库做出响应
req.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); PrintWriter writer=resp.getWriter(); String handle=req.getParameter("handle"); String account=req.getParameter("name"); System.out.println("handle="+handle+",account="+account); Connection conn=null; try { conn=DBUtil.getConnection(); String sql="select * from person"; PreparedStatement psmt=conn.prepareStatement(sql); ResultSet rs=psmt.executeQuery(); ResultSetMetaData rsm=rs.getMetaData(); int num=rsm.getColumnCount(); JSONObject json=new JSONObject(); JSONObject user=new JSONObject(); while(rs.next()) { String name=rs.getString("name"); json.put("code", "0"); json.put("message", "success"); if(account.equals(name)) { for(int i=1; i<=num; i++){ user.put(rsm.getColumnName(i), rs.getObject(i)); } json.put("data", user); System.out.println(json.toString()); writer.write(json.toString()); writer.flush(); writer.close(); } } } catch (Exception e) { e.printStackTrace(); }finally { DBUtil.closeConnection(conn); }

关于json数据和实体类的转化
Person person=(Person) JSONObject.toBean(user,Person.class); //json转person实体类 System.out.println(person.getName()); System.out.println(person); JSONObject data=https://www.it610.com/article/JSONObject.fromObject(person); //person实体类转json System.out.println(data.get("name")); System.out.println(data.toString());

    推荐阅读