自定义HTTPMessageConverter接收JSON格式的数据

时间:2023-01-01 16:40:10

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'json2.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testjson2();
});
function testjson2(){
$.ajax({
url:"${pageContext.request.contextPath}/json/testRequestBody.htm",
dataType:"json",//预期服务器返回的类型
type:"post",
contentType:"application/json",//发送信息到服务器时编码格式
//发送到服务器的数据
data:JSON.stringify({id:1,name:"SpringMVC 企业应用实战"}),
async:true,//表示异步
success:function(data){
$("#id").html(data.id);
$("#name").html(data.name);
$("#auther").html(data.auther);
},
error:function(){
alert("数据发送失败");
}
});
}
</script>
</head>
<body>
编号:<span id="id"></span><br>
书名:<span id="name"></span><br>
作者:<span id="auther"></span><br>
</body>
</html>

controller类
package com.anbow.controller;

import java.io.IOException;

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.anbow.bean.Book;
@Controller
@RequestMapping(value=”/json”)
public class BookController {

@RequestMapping(value="/testRequestBody")
public void setJson(@RequestBody Book book,HttpServletResponse response){
//JsonObject-lib是一个beans,controllers,maps,Java arrays 和xml和json互相转换的包
book.setAuther("乔峰");
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print(JSONObject.toJSONString(book));
} catch (IOException e) {
e.printStackTrace();
}
}

}

servlet-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
default-autowire="byName">


<!-- spring可以自动扫描有base package下面的包或者是子包下面的Java文件
如果扫描到有spring的相关注解的类,则把这些类注册为spring的bean
-->

<context:component-scan base-package="com.anbow"></context:component-scan>
<!-- 使用默认的servlet来响应静态文件 -->
<mvc:default-servlet-handler/>
<!-- 设置配置方案 -->
<mvc:annotation-driven>
<!-- 设置不使用默认的消息转换器 -->
<mvc:message-converters register-defaults="false">
<!-- 配置spring的转换器 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"></bean>
<!-- 配置fastjson 中实现HttpMessageConverter接口的转换器 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型 -->
<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/jsp</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>

</bean>


</beans>