1. 程式人生 > >自定義HttpMessageConverter接受JSON格式的數

自定義HttpMessageConverter接受JSON格式的數

 1.配置修改

<?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.control"/>
	<!-- 使用預設的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>

 注:以上的配置檔案和和之前的配置檔案重點的區別在於,之前使用的是Spring中預設的Mapping-Jackson2HttpMessageConverter,這樣只需要配置預設的<mvc:annotation-driven/>就可以了。而現在使用了第三方的fastjson處理json資料,則需要另行配置HttpMessageConverter。

2.前端

 index.jsp

<%@ 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 : "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>
編號:<span id="id"></span><br>
書名:<span id="name"></span><br>
作者:<span id="author"></span><br>
</body>
</html>

3.後端

 Book.java

package com.bean;

import java.io.Serializable;

public class Book implements Serializable {
	private Integer id;
	private String name;
	private String 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() {
		// TODO Auto-generated method stub
		return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
	}
	
}

BookController.java
package com.control;

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.alibaba.fastjson.JSONObject;
import com.bean.Book;

@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{
    	// JSONObject-lib包是一個beans,collections,maps,java arrays和xml和JSON互相轉換的包。
    	// 使用JSONObject將book物件轉換成json輸出
    	logger.info(JSONObject.toJSONString(book));
    	book.setAuthor("海哥");
    	response.setContentType("text/html;charset=UTF-8");
    	// 將book物件轉換成json寫出到客戶端
    	response.getWriter().println(JSONObject.toJSONString(book));
    }
}

4.截圖