Spring默認使用Jackson處理json數據。實際開發中,在業界中,使用非常受歡迎的fastjson來接受json數據。
創建一個項目,在web目錄下新建一個assets/js目錄,加入jquery和json2的js文件,在lib下加入fastjson的jar文件。
BookController
package com.wen.controller;
import com.alibaba.fastjson.JSONObject;
import com.wen.domain.Book;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class BookController {
private static final Log logger = LogFactory.getLog(Book2Controller.class);
@RequestMapping(value = "/testRequestBody")
public void setJson(@RequestBody Book book, HttpServletResponse response) throws IOException {
//使用JsonObject將book對象轉換成json輸出
logger.info(JSONObject.toJSONString(book));
book.setAuthor("xiaoxiaorui");
response.setContentType("text/html;charset=UTF-8");
//將book對象轉換成json寫出客戶端
response.getWriter().println(JSONObject.toJSONString(book));
}
}
配置springmvc-config.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--spring可以自動去掃描base-pack下面的包或者子包下面的java文件,
如果掃描到有Spring的相關注解的類,則把這些類注冊為Spring的bean-->
<context:component-scan base-package="com.wen.controller"/>
<!--設置默認的Servlet來響應靜態文件-->
<mvc:default-servlet-handler/>
<!--設置配置方案,會自動注冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean-->
<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接口的轉換器-->
<!--FastJsonHttpMessageConverter是fastjson中實現了HttpMessageConverter接口的類-->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!--加入支持的媒體類型:返回contentType-->
<property name="supportedMediaTypes">
<list>
<!--這里順序一定不能寫反,不然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/pages/"/>
<!--后綴-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--定義Spring MVC前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--讓Spring MVC的前端控制器攔截所有請求-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%--
Created by IntelliJ IDEA.
User: wen
Date: 2019/2/10
Time: 12:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>測試接受JSON格式的數據</title>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
testRequestBody();
})
function testRequestBody() {
$.ajax({
dataType:"json",//預期服務器返回的數據類型
type:"post",//請求方式post 或 get
url:"${pageContext.request.contextPath}/testRequestBody",//發送請求的URL字符串
contentType:"application/json",//發送信息至服務器時的內容編碼格式
data:JSON.stringify({id:1,name:"SpringMVC企業應用實戰"}),
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>
其實處理json格式的開源類包使用Jackson和fastjson,只是需要使用不同的HttpMessageConverter。