SpringMVC轉換JSON數據(1)

SpringMVC提供了處理JSON格式請求/響應的        HttpMessageConverter:MappingJackson2HttpMessageConverter。利用Jackson開源類包處理JSON格式的請求或響應消息。

我們需要做的:

  1. 在Spring容器中爲RequestmappingHandlerAdapter裝配處理JSON的HttpMessageConverter

  2. 在交互過程中請求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

源代碼:http://down.51cto.com/data/2300368

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章