1. 程式人生 > >使用fastjson與SpringMVC實現自定義HttpMessageConverter接收和獲取JSON格式的資料

使用fastjson與SpringMVC實現自定義HttpMessageConverter接收和獲取JSON格式的資料

1.下載Spring、fastjson的jar包以及jQuery和json2的js檔案,向專案的WEB-INF/lib目錄加入Spring和fastjson的jar包,在WebContent目錄下建立一個js資料夾,向js資料夾中加入jQuery和json2的js檔案。

2.配置web.xml:配置SpringMVC前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FastjsonRequestTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
     <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <!-- 讓servlet隨服務啟動 -->
  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

3.編寫實體類(bean):

package com.domain;

import java.io.Serializable;

public class Book implements Serializable{

	private Integer id;
	private String name;
	private String author;
	public Book() {
		// TODO Auto-generated constructor stub
	}
	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 + "]";
	}
	
}


4.編寫index.jsp:

<%@ 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-3.2.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("testRequestBody.action",
	{
		dataType : "json",
		type : "post",
		contentType : "application/json",
		data : JSON.stringify({"id" : 1, "name" : "Spring MVC學習"}),
		async : true,
		success : function(data){
			console.log(data);
			$("#id").html(data.id);
			$("#name").html(data.name);
			$("#author").html(data.author);
		},
		error:function(){
			alert("資料傳送失敗");
		}
	});
}
</script>
</head>
<body>
<button id="btn">點選</button><br>
編號:<span id="id"></span><br>
書名:<span id="name"></span><br>
作者:<span id="author"></span><br>
</body>
</html>

5.編寫handler處理器:BookController.java

package com.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

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.domain.Book;

@Controller
public class BookController {

	@RequestMapping(value="/testRequestBody")
	public void setJson(
			@RequestBody Book book,
			HttpServletResponse response
			) throws IOException{
		book.setAuthor("張三");
		response.setContentType("text/html;charset=UTF-8");
		//JSONobject-lib包是一個beans,collections,maps,java arrays和xml與JSON互相轉換的包
		//使用JSONobject將book物件轉換成json寫出到客戶端
		PrintWriter out =  response.getWriter();
		out.println(JSONObject.toJSONString(book));
	}
}

6.配置SpringMVC配置檔案:springmvc.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:tx="http://www.springframework.org/schema/tx" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:c="http://www.springframework.org/schema/c"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
  		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  		http://www.springframework.org/schema/mvc
  		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  		http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	<!-- 自動掃描base-package所指定包下面的java檔案,如果掃描到右Spring相關注解的類,則把這些類註冊為Spring的bean -->
	<context:component-scan base-package="com.controller"/>
	<!-- 實際開發中使用<mvc:annotation-driven/>代替註解介面卡和對映器 -->
	<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>
						<!-- 這裡順序不能寫反,一定要先寫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>
	<!-- 載入靜態檔案 -->
	<mvc:default-servlet-handler/>
	<!-- 配置檢視解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 字首 
		<property name="prefix">
			<value>/WEB-INF/</value>
		</property>-->
		<!-- 字尾 -->
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
	
</beans>

執行前index.jsp顯示如下:


執行點選後,結果如下: