小編給大家分享一下SpringMVC如何轉換JSON數據,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
SpringMVC提供了處理JSON格式請求/響應的 HttpMessageConverter:MappingJackson2HttpMessageConverter。利用Jackson開源類包處理JSON格式的請求或響應消息。
我們需要做的:
在Spring容器中為RequestmappingHandlerAdapter裝配處理JSON的HttpMessageConverter
在交互過程中請求Accept指定的MIME類型
org.springframework.web.bind.annotation.RequestBody注解用于讀取Request請求的body部分數據,使用系統默認配置的HttpMessageConverter進行解析,然后把響應的數據綁定到Controller中的方法的參數上。
數據編碼格式由請求頭的ContentType指定。它分為以下幾種情況:
1.application/x-www-form-urlencoded,這種情況的數據@RequestParam、@ModelAttribute也可以處理,并且很方便,當然@RequestBody也可以處理。
2.multipart/form-data,@RequestBody不能處理這種數據格式的數據。
3.application/json、application/xml等格式的數據,必須使用@RequestBody來處理。
在實際開發當中使用@RequestBody注解可以方便的接收JSON格式的數據,并將其轉換為對應的數據類型。
DEMO:接收JSON格式的數據:
1.index.jsp
testRequestBody函數發送異步請求到“json/testRequestBody”,其中:contentType:"application/json"表示發送的內容編碼格式為json格式,data:JSON.stringify(....)表示發送一個json數據;請求成功后返回一個json數據,接收到返回的json數據后將其設置到span標簽中
<%@ 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(
{
url:"${pageContext.request.contextPath}/json/testRequestBody",
dateType:"json",
type:"post",
contentType:"application/json",
data:JSON.stringify({id:1,name:"老人與海"}),
async:true,
success:function(data){
alert("成功");
alert(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>
書名:<span id="name"></span>
作者:<span id="author"></span>
</body>
</html>2.Book實體類
package com.cn.domain;
import java.io.Serializable;
public class Book implements Serializable {
private Integer id;
private String name;
private String author;
public Book(){
super();
}
public Book(Integer id, String name, String author) {
super();
this.id = id;
this.name = name;
this.author = author;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}3.BookController
setJson方法中的第一個參數@RequestBody Book book,使用@RequestBody注解獲取到json數據,將json數據設置到對應的Book對象的屬性中。第二個參數是HttpServletResponse對象,用來輸出響應數據到客戶端。
package com.cn.controller;
import javax.servlet.http.HttpServletResponse;
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 com.cn.domain.Book;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping("/json")
public class BookController {
private static final Log logger = LogFactory.getLog(BookController.class);
@RequestMapping(value="/testRequestBody")
public void setJson(@RequestBody Book book, HttpServletResponse response) throws Exception{
//注意ObjectMapper類是Jackson庫的主要類。負責將java對象轉換成json格式的數據。
ObjectMapper mapper = new ObjectMapper();
logger.info(mapper.writeValueAsString(book));
book.setAuthor("海明威");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(mapper.writeValueAsString(book));
}
}4.springmvc-config
(1)<mvc:annotation-drive>會自動注冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean,這是SpringMVC為@Controllers分發請求所必須的,并提供了數據幫頂支持、@NumberFormatannotation支持、@DateTimeFormat支持、@Valid支持、讀寫XML的支持一記讀寫JSON的支持等功能。本例處理ajax請求就用到了對JSON功能的支持。
(2)<mvc:default-servlet-handler/>使用默認的Servlet來響應靜態文件,因為在web.xml中使用了DispatcherServlet截獲所有請求的url,而本例引入的js/jquery-1.11.0.min.js以及js/json2.js文件的時候,DispatcherServlet會將"/"看成請求路徑,就會報404的錯誤。而當配置文件加上這個默認的Servlet時,Servlet在找不到它時會去找靜態的內容。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd "> <!-- Spring 可以自動去掃描base-pack下面的包或者子包下面的java文件 --> <!-- 如果掃描到spring相關的注解類,將其注冊為spring的bean --> <context:component-scan base-package="com.cn.controller" /> <!-- 設置配置方案 --> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <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>
需要添加的jar包:Spring的所有jar、commons-logging.jar以及Jackson相關的jar
需要引入的js:jquery.js、json2.js
以上是“SpringMVC如何轉換JSON數據”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。