6.JSON數(shù)據(jù)處理
6.1.添加json依賴
springmvc 默認(rèn)使用jackson作為json類庫(kù),不需要修改applicationContext-servlet.xml任何配置,只需引入以下類庫(kù)springmvc就可以處理json數(shù)據(jù):
<!--spring-json依賴-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
6.2.注解
- @RequestBody:作用是接收前端ajax傳遞給后端的json字符串,并將json格式的數(shù)據(jù)轉(zhuǎn)為java對(duì)象
- @ResponseBody:作用是將java對(duì)象轉(zhuǎn)為json格式的數(shù)據(jù)傳遞給前臺(tái)ajax
6.3.案例
-
編寫controller
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping("/saveAccount2") @ResponseBody public Map saveAccount2(@RequestBody Account account){ Map<String, Object> map = new HashMap<String, Object>(); map.put("status",200); map.put("msg",account); return map; } }
-
在index.jsp里面定義ajax請(qǐng)求
-
添加按鈕
<input type="button" value="測(cè)試ajax請(qǐng)求json和響應(yīng)json" id="testJson"/>
-
引入js庫(kù)文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
-
編寫ajax代碼文章來源:http://www.zghlxwxcb.cn/news/detail-801435.html
<script type="text/javascript"> $(function(){ $("#testJson").click(function(){ $.ajax({ type:"post", url:"/account/saveAccount2", contentType:"application/json;charset=UTF-8", data:'{"id":1,"name":"張二狗","money":999.0}', success:function(data){ if(data.status == 200){ alert(data.msg.name); alert(data.msg.money); } } }) }); }) </script>
-
-
測(cè)試
文章來源地址http://www.zghlxwxcb.cn/news/detail-801435.html
到了這里,關(guān)于SpringMVC JSON數(shù)據(jù)處理見解6的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!