SpringMVC 返回json的兩種方式

先後臺數據交互使用json是一種很重要的方式.本文主要探討SpringMVC框架使用json傳輸的技術.html

請注意,本文所提到的項目使用Spring 版本是4.1.7,其餘版本在具體使用上可能有不同的狀況.java

1、最多見——使用@RequestBody的註解返回一個實體對象;jquery

使用方式以下:ajax

1:引入jar包:json

jackson-core、jackson-databind、jackson-annotion;瀏覽器

Spring4以上的版本這麼配置,須要jackson的版本在2以上.tomcat

maven依賴mvc

 
 
<properties>
<jackson.version>2.7.3</jackson.version>
</properties>

<!--
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency>

2:Spring配置:app

<mvc:annotation-driven/>

Spring4以上版本使用 <mvc:annotation-driven/>即包含了默認的配置,可以轉化json,其餘版本可能須要額外配置.框架

3:後臺:

@RequestMapping("/entity")
    public @ResponseBody Entity returnJson(){
        return new Entity("chentao","A handsome man");
    }

關鍵就是@ResponseBody註解,不然Spring會去映射與路徑匹配的jsp文件

4:前臺

這個路徑是能夠直接調用的,結果會直接輸出到,可是通常來講,會使用jquery Ajax來獲取數據:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Welcome Page</title>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
    <script
            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
</head>
<body>
     <h2>Hello World!</h2>
<div id="div1">
</div>
</body>
<script> $.get("/json/entity",function (data) { $("#div1").html(data); }) </script>
</html>

結果

 

a:不添加@ResponseBody註解的狀況,經過連接註解訪問:

 

 

能夠看到Spring MVC框架這個時候去找/json/entity.jsp這個文件的.

 

b:添加@ResponseBody註解後:

 

json數據能正確返回了.

 

2、更加靈活的方式——將json數據放進Request中交互。

Spring MVC使用@ResponseBody的方式確實很簡單,可是咱們有時也會遇到這樣的場景 ,就是訪問一個新頁面時,可能既要找到新的頁面又要拿到新的數據去繪製頁面。

這種時候若是使用@ResponseBody這種方式,那麼就須要使用ajax技術,向後臺請求兩次,一次請求頁面,一次請求數據。

若是但願經過一次請求就完成這個目標,那麼就應該返回一個ModelAndView的對象,這樣SpringMVC既能夠跳轉到一個頁面,也能把數據傳輸到Request中。

使用方式:

1:相關jar包:

使用對象轉化爲Json的相關jar包,通常來講使用的時json-lib,實際上相似的框架和技術還有不少,好比上面的jackson就能作,不過筆者習慣於使用json-lib,使用起來會更方便和順手一點。

maven:   

<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>

2:Spring 配置:無

3:後臺:

@RequestMapping("/page")
    public ModelAndView returnView(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("showJson");

        Entity entity = new Entity("chentao","a handsome man");

        JSONObject entityJson = JSONObject.fromObject(entity);

        mv.addObject("entityJson",entityJson);
        return mv;
    }

關鍵是JSONObject.fromObject()方法。

4:前臺:

<script>
    var json = ${entityJson};
    alert(json);
</script>

注意這裏的El表達式寫法${entityJson},瀏覽器在進行渲染以前,tomcat已經將${entityJson}替換爲json字符串。這個時候json直接就是一個可使用的對象而再也不須要進行轉化

結果以下;

 

注意,這種方式只有在jsp頁面中才有效果,若是不是jsp頁面,只能乖乖使用第一種方式了。

3、總結

  @Response註解的方式 返回ModelAndView方式
優勢 編寫簡單;適合當前ajax方式; 更加靈活,頁面和數據一同返回。
缺點 靈活性不足

須要手動轉化json;

前臺接受數據只能用在jsp頁面裏。

實現要點 @ResponseBody;jackson-jar包;ajax; JsonObject.fromObject();El表達式:${}.
     

 

4、擴展

本文檔使用的是SpringMVC框架,實際上第一種方式本質上是使用Response的writer對象來傳遞數據,而第二種方式使用request傳遞數據。因此若是使用原生servlet或者其餘框架也是可以實現相似的功能的。

相關文章
相關標籤/搜索