fastjson和SpringMVC實現自定義HttpMessageConverter接收和獲取JSON格式的資料
**引言**:Spring MVC 提供了處理JSON格式請求/響應的HttpMessageConverter利用Jackson 開源包處理JSON格式的請求響應訊息。
```"關鍵技術"```:
**RequestBody**註解 :用於讀取Request請求的Body部分資料,使用系統預設配置的HttpMessageConverter進行解析,然後把相應的資料繫結到Controller中的方法引數上。
(實際開發中,使用@RequestBody註解可以很方便地接收JSON資料,並將其裝換為對應的資料型別)
資料編碼格式由請求頭 ContentType 指定:
application/json 、 application/xml 等格式的資料,必須使用@RequestBody來處理
操作流程:
操作json:
1. 在前端使用ajax傳送寄送資料:
2. 在處理器中使用 @RequestBody將請求json資料裝換為實體物件
後端向前端傳送json資料
1. 處理器通過HttpServletResponse 的 getWriter() 方法獲取的(out)物件向前端返回資料
2. 在前端解析返回的json 資料
具體例項(兩種方式):
1.使用Jackson的jar包,原生ajax方式。我下的是2.5版本, 要下載的網上搜索就可以 了
測試jsp頁面和ajax 程式碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>json 測試</title> </head> <body> <button onclick="show()"> 獲取json</button> <div id="msg"></div> </body> </html> <script type="text/javascript"> function show(){ var xmlhttp;// 用於實現和伺服器的互動 if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, // Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var str = xmlhttp.responseText; var obj = JSON.parse(str); //將字串轉換為 json物件 document.getElementById("msg").innerHTML =obj.name ; } } xmlhttp.open("POST", "test.action", true); // 建立和伺服器的連結 xmlhttp.setRequestHeader("Content-type", "application/JSON; charset=utf-8"); //設定請求頭 var data = JSON.stringify(//將字串格式的資料轉換為JSON { id:4, "name":"wangwu" } ) xmlhttp.send(data);// 傳送請求 } </script>
ajax 會將請求傳送到對映地址為test 的Controller裡面去處理
程式碼如下:
@Controller
public class MyHandler {
@RequestMapping("/test")
public void returnBack(@RequestBody User user,HttpServletResponse response) throws IOException{
ObjectMapper mapper = new ObjectMapper();//將User物件轉換json輸出
response.getWriter().print(mapper.writeValueAsString(user));//將物件轉換為json字串
//@RequestBody User user 將請求json資料裝換為實體物件
}
}
User 實體類
public class User {
private Integer id;
private String name;
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 User(){}
public User(Integer id,String name){
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
配置SpringMVC.xml檔案
<!-- 將註解的類,掃描載入 第三種方式 註解方式 -->
<context:component-scan base-package="com.mt.controller" />
<!-- 實際開發中使用 <mvc:annotation-driven/>代替註解介面卡和對映器 -->
<mvc:annotation-driven/>
<!-- 使用預設的servlet 來響應靜態檔案 -->
<mvc:default-servlet-handler/>
<!-- 配置檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
最後我們在瀏覽器上面測試,測試結果如下:
點選按鈕
2.第二種方式,使用使用 fastjson的jar包, 和jQuery框架的ajax 實現。()
步驟:
1.首先 需要去下載 fastjson(只有一個包)和jQuery的架包, 好像fastjson是alibaba公司的 。網上百度,這種方式的架包,比較小
2.配置springmvc.xml 檔案 (fastjson需要配置比較多的xml檔案相比 上一中方法)
(注意,這裡都用的是SpringMVC框架,所以在web.xml 當中的配置 基本是一樣的這裡就不再累述)
<!-- spring可以自動去掃描base-pack下面的包或者子包下面的java檔案,
如果掃描到有Spring的相關注解的類,則把這些類註冊為Spring的bean -->
<context:component-scan base-package="com.mt.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>
3.JSP測試程式碼 和jQuery的ajax程式碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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(){
$("#btn").click(testRequestBody);
});
function testRequestBody(){
$.ajax("${pageContext.request.contextPath}/json/testRequestBody.action",// 傳送請求的URL字串。
{
dataType : "json", // 預期伺服器返回的資料型別。
type : "post", // 請求方式 POST或GET
contentType:"application/json", // 傳送資訊至伺服器時的內容編碼型別
// 傳送到伺服器的資料。
data:JSON.stringify({"id" : 1, "name" : "Spring MVC企業應用實戰"}),
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>
<h1>jquery ajax</h1>
<button id="btn">點選顯示</button>
編號:<span id="id"></span><br>
書名:<span id="name"></span><br>
作者:<span id="author"></span><br>
</body>
</html>
4.控制器當中的程式碼@Controller
@RequestMapping("/json")
public class BookJSONController {
private static final Log logger = LogFactory.getLog(BookJSONController.class);
// @RequestBody根據json資料,轉換成對應的Object
@RequestMapping(value = "/testRequestBody")
public void setJson(@RequestBody Book book, HttpServletResponse response) throws Exception {
// ObjectMapper類是Jackson庫的主要類。它提供一些功能將Java物件轉換成對應的JSON格式的資料
System.out.println(111);
book.setAuthor("肖文吉");
ObjectMapper mapper = new ObjectMapper();
// 將book物件轉換成json輸出
logger.info(mapper.writeValueAsString(book));
response.setContentType("text/html;charset=UTF-8");
// 將book物件轉換成json寫出到客戶端
response.getWriter().println(mapper.writeValueAsString(book));
}
}
Book實體類:
public class Book implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4521962093312030024L;
private Integer id;
private String name;
private String author;
public Book(){}
public Book(Integer id,String name,String author){
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;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
}
}
測試資料如下:
注意:
在Springmvc中如果引入了其他靜態檔案(圖片,css,js。)需要在配置檔案中新增
<!-- 使用預設的Servlet來響應靜態檔案 -->
<mvc:default-servlet-handler/>
表示如果沒有找到對應 請求的處理器,那麼就直接用載入檔案方式處理
總結: 在SpringMVC框架的基礎上。 以上我們實現了從js字串轉換為json格式的物件,在將其傳入控制器,通過@RequestBody註解 將其轉換為 對應的資料實體類,操作完成後,然後在將對應的資料實體類,轉換為json資料,傳出。 JSP頁面通過ajax來接收,顯示到頁面上。