自定义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

时间: 2024-07-30 11:38:11

自定义HttpMessageConverter接受JSON数据的相关文章

PHP自定义函数格式化json数据怎么调用?

<?php/*** Formats a JSON string for pretty printing** @param string $json The JSON to make pretty* @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks* @return string The prettified output*/$arr = array("ret"

json数据基础讲解

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言.易于人阅读和编写,同时也易于机器解析和生成. 基础结构 JSON建构于两种结构: 1. "名称/值"对的集合(A collection of name/value pairs).不同的语言中,它被理解为对象(object),记录(record),结构(struct),字典(dictionary),哈希表(hash

ajax请求从js传json数据到后场及接受方式—用或者不用RequestBody的情况及后场返回

参考网上队友的帖子:传递JSON数据有没有必要用RequestBody?https://www.cnblogs.com/NJM-F/p/10407763.html 1.不使用RequestBody时是这样的: 前端参数可以直接使用JSON对象: //此时请求的ContentType默认是application/x-www-form-urlencoded: var user= { "username" : username, "password" : password

Spring MVC如何进行JSON数据的传输与接受

本篇文章写给刚接触SpingMVC的同道中人,虽然笔者本身水平也不高,但聊胜于无吧,希望可以给某些人带来帮助 笔者同时再次说明,运行本例时,需注意一些配置文件和网页脚本的路径,因为笔者的文件路径与读者的未必相同 首先准备以下 jar包:commons-logging-1.1.3.jarjackson-core-asl-1.9.2.jarjackson-mapper-asl-1.9.2.jarspring-aop-4.0.6.RELEASE.jarspring-beans-4.0.6.RELEAS

Android与PHP交互,Android传递JSON数据,PHP接受并保存数据

突然想到这样一个功能,用户使用某客户端登陆的时候,客户端做了以下两件事,一个是跳转页面,返回个人信息:第二个是将信息返回到服务器,服务器将数据保存在数据库中.这样一来用户的个人信息也就获取到了! 事不宜迟赶快实现吧! 正好我的SAE云豆还没有消耗完,我就打算用PHP做后台! 客户端与服务端传送现在比较流行传递Json字符串!(还好之前了解过Json),android将数据包装成Json格式,然后通过Httpclient发送给PHP后台,php根据属性名得到Json字符串,然后做出解析,最后保存(

spring之json数据的接受和发送

配置spring对json的注解方式. <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > <property name="messageConverters"> <list > <ref bea

springMVC接受json类型数据

springMVC接受json格式的数据很简单 使用@RequestBody 注解,标识从请求的body中取值 服务端示例代码 @RequestMapping(value = "/t4", method = RequestMethod.POST) @ResponseBody public Result t3(@RequestBody SysUser user) { Result r = Result.success(); r.setData(user); return r; } 客户端

httpClient post方法 解析json数据(向服务器传递,接受服务器传递)

import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEnt

springMVC接受ajax提交表单,json数据的两种方式

作为一个初入互联网行业的小鑫鑫,在使用springMVC时发现一个好耍的东西,决定记下来,免得哪天忘了,哈哈 第一种 序列化表单,将表单数据序列化为json对象字符串 $("#submit").click(function (){ var form=$("form").serializeArray(); $.ajax({ url:"${pageContext.request.contextPath}/teacher/updateTeacher",