json是一種常見的傳遞格式,是一種鍵值對應的格式。而且數據大小會比較小,方便傳遞。因此在開發中常常會用到json。javascript
首先看一下json的格式:css
{key1:value1,key2:value2}html
每個建對應一個值,每一個鍵值對之間用逗號鏈接。而且最後一個鍵值對以後沒有逗號,總體須要有大括號括起來。java
SpringMVC的前臺獲取json代碼:jquery
annotationTest.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'annotationTest.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="/Spring6Annotation3/js/jquery-1.7.js"></script> </head> <script type="text/javascript"> $(document).ready(function(){ $("#submit").click( function(){ var username = $("#username").attr("value"); var userage = $("#userage").attr("value"); var userJson={name:username,age:userage};//構造json數據 $.ajax({ url:"/Spring6Annotation3/user/data/showInfoJson", type:"post", data:userJson, success: function(data){ alert("name===>"+data.username+"age"+data.userage); }//由此咱們能夠看出,jquary中的ajax也是json格式的 }); }); }); </script> <body> <h1>json</h1> <br/> <form action=""> 姓名:<input type="text" id="username" name="name"/> 年齡:<input type="text" id="userage" name="age"/> <input type="button" id="submit" value="提交"/> </form> </body> </html> 在controller中 @RequestMapping("/showInfoJson") public void showInfoJson(User user,HttpServletRequest request,HttpServletResponse response){ String result = "{\"username\":\""+user.getName()+"\",\"userage\":\""+user.getAge()+"\"}";//user接到前臺傳到的數據,並拼接成新的json對象 response.setContentType("application/json");//設置response的傳輸格式爲json System.out.println(result); try { PrintWriter out = response.getWriter(); out.write(result)//給頁面上傳輸json對象 } catch (IOException e) { e.printStackTrace(); } }