springmvc處理json數據

springMVC提供了處理JSON格式請求/響應的HttpMessageConverter

MappingJckson2HttpMessageConverter利用Jackson開源類包處理JSON格式的請求或響應

index.jspjavascript

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSON格式的數據接受</title>
    <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="js/json2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            testRequestBody();
        });
        function testRequestBody() {
            $.ajax("${pageContext.request.contextPath}/json/testRequestBody",// 發送請求的URL字符串。
                {
                    dataType: "json", // 預期服務器返回的數據類型。
                    type: "post", //  請求方式 POST或GET
                    contentType: "application/json", //  發送信息至服務器時的內容編碼類型
                    // 發送到服務器的數據。
                    data: JSON.stringify({id: 1, name: "張三"}),
                    async: true, // 默認設置下,全部請求均爲異步請求。若是設置爲false,則發送同步請求
                    // 請求成功後的回調函數。
                    success: function (data) {
                        console.log(data);
                        $("#id").html(data.id);
                        $("#name").html(data.name);
                        $("#author").html(data.author);
                    },
                    // 請求出錯時調用的函數
                    error: function () {
                        alert("數據發送失敗");
                    }
                });
        }
    </script>
</head>
<body>
編號:<span id="id"></span><br>
書名:<span id="name"></span><br>
做者:<span id="author"></span><br>
</body>
</html>

BookController.javahtml

package com.rookie.bigdata.controller;

import javax.servlet.http.HttpServletResponse;

import com.rookie.bigdata.domain.Book;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/json")
public class BookController {

    private static final Log logger = LogFactory.getLog(BookController.class);

    // @RequestBody根據json數據,轉換成對應的Object
    @RequestMapping(value="/testRequestBody")
    public void setJson(@RequestBody Book book,
            HttpServletResponse response) throws Exception{
        // ObjectMapper類是Jackson庫的主要類。它提供一些功能將Java對象轉換成對應的JSON格式的數據
        ObjectMapper mapper = new ObjectMapper();
        // 將book對象轉換成json輸出
        logger.info(mapper.writeValueAsString(book) );
        book.setAuthor("許文強");
        response.setContentType("text/html;charset=UTF-8");
        // 將book對象轉換成json寫出到客戶端
        response.getWriter().println(mapper.writeValueAsString(book));
    }

}

springmvc-config.xmljava

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <!-- spring能夠自動去掃描base-pack下面的包或者子包下面的java文件,
        若是掃描到有Spring的相關注解的類,則把這些類註冊爲Spring的bean -->
    <context:component-scan base-package="org.fkit.controller"/>
    <!-- 設置配置方案  -->
    <mvc:annotation-driven/>
    <!-- 使用默認的Servlet來響應靜態文件 -->
    <mvc:default-servlet-handler/>


    <!-- 視圖解析器  -->
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前綴 -->
        <property name="prefix">
            <value>/WEB-INF/content/</value>
        </property>
        <!-- 後綴 -->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

啓動應用程序返回的截圖以下
jquery

自定義HttpMessageConverter接受JSON格式的數據,採用fastJson來接受JSON數據

將上面的controller代碼改成web

@RequestMapping(value="/testRequestBody")
    public void setJson(@RequestBody Book book,
            HttpServletResponse response) throws Exception{
        // 使用JSONObject將book對象轉換成json輸出
        logger.info(JSONObject.toJSONString(book));
        book.setAuthor("zhangsan");
        response.setContentType("text/html;charset=UTF-8");
        // 將book對象轉換成json寫出到客戶端
        response.getWriter().println(JSONObject.toJSONString(book));
    }

配置文件改成下面這個便可跟前面訪問的效果同樣ajax

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.2.xsd">
        
    <!-- spring能夠自動去掃描base-pack下面的包或者子包下面的java文件,
        若是掃描到有Spring的相關注解的類,則把這些類註冊爲Spring的bean -->
    <context:component-scan base-package="com.rookie.bigdata.controller"/>
    <!-- 使用默認的Servlet來響應靜態文件 -->
    <mvc:default-servlet-handler/>
    <!-- 設置配置方案 -->
    <mvc:annotation-driven>
        <!-- 設置不使用默認的消息轉換器 -->
        <mvc:message-converters register-defaults="false">
            <!-- 配置Spring的轉換器 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
            <!-- 配置fastjson中實現HttpMessageConverter接口的轉換器 -->
            <bean id="fastJsonHttpMessageConverter" 
                class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <!-- 加入支持的媒體類型:返回contentType -->
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 這裏順序不能反,必定先寫text/html,否則ie下會出現下載提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    
    <!-- 視圖解析器  -->
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <!-- 前綴 -->
        <property name="prefix">
            <value>/WEB-INF/content/</value>
        </property>
        <!-- 後綴 -->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
</beans>

返回JSON數據格式

@RequestMapping(value="/testresponse")
    // @ResponseBody會將集合數據轉換json格式返回客戶端
    @ResponseBody
    public Object getJson() {
        List<Book> list = new ArrayList<Book>();
        list.add(new Book(1,"java","lisi"));
        list.add(new Book(2,"徐文清","wangwu"));
        return list;
    }
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>測試返回JSON格式的數據</title>
    <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="js/json2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            testResponseBody();
        });
        function testResponseBody(){
            $.post("${pageContext.request.contextPath}/json/testresponse",null,
                function(data){
                    $.each(data,function(){
                        var tr  = $("<tr align='center'/>");
                        $("<td/>").html(this.id).appendTo(tr);
                        $("<td/>").html(this.name).appendTo(tr);
                        $("<td/>").html(this.author).appendTo(tr);
                        $("#booktable").append(tr);
                    })
                },"json");
        }
    </script>
</head>
<body>
<table id="booktable" border="1"  style="border-collapse: collapse;">
    <tr align="center">
        <th>編號</th>
        <th>書名</th>
        <th>做者</th>
    </tr>

</table>

</body>
</html>
相關文章
相關標籤/搜索