自定义HttpMessageConverter接受JSON数据

Spring默认使用Jackson处理json数据。实际开发中,在业界中,使用非常受欢迎的fastjson来接受json数据。

创建一个项目,在web目录下新建一个assets/js目录,加入jquery和json2的js文件,在lib下加入fastjson的jar文件。

BookController

package com.wen.controller;

import com.alibaba.fastjson.JSONObject;
import com.wen.domain.Book;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class BookController {
    private static final Log logger = LogFactory.getLog(Book2Controller.class);

    @RequestMapping(value = "/testRequestBody")
    public void setJson(@RequestBody Book book, HttpServletResponse response) throws IOException {
        //使用JsonObject将book对象转换成json输出
        logger.info(JSONObject.toJSONString(book));
        book.setAuthor("xiaoxiaorui");
        response.setContentType("text/html;charset=UTF-8");
        //将book对象转换成json写出客户端
        response.getWriter().println(JSONObject.toJSONString(book));
    }

}

配置springmvc-config.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
    如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean-->
    <context:component-scan base-package="com.wen.controller"/>
    <!--设置默认的Servlet来响应静态文件-->
    <mvc:default-servlet-handler/>
    <!--设置配置方案,会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean-->
    <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>
                        <!--这里顺序一定不能写反,不然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/pages/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--定义Spring MVC前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--让Spring MVC的前端控制器拦截所有请求-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: wen
  Date: 2019/2/10
  Time: 12:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>测试接受JSON格式的数据</title>
    <script type="text/javascript" src="assets/js/jquery.js"></script>
    <script type="text/javascript" src="assets/js/json2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            testRequestBody();
        })
        function testRequestBody() {
           $.ajax({
               dataType:"json",//预期服务器返回的数据类型
               type:"post",//请求方式post 或 get
               url:"${pageContext.request.contextPath}/testRequestBody",//发送请求的URL字符串
               contentType:"application/json",//发送信息至服务器时的内容编码格式
               data:JSON.stringify({id:1,name:"SpringMVC企业应用实战"}),
               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>

其实处理json格式的开源类包使用Jackson和fastjson,只是需要使用不同的HttpMessageConverter。

原文地址:https://www.cnblogs.com/guowenrui/p/10363589.html