最近的项目没有用到这个,先把自己自学跑通的例子先帖出来,供自己以后参考吧!

如有不对地方望指出!

一、自定义类实现AbstractHttpMessageConverter

 package com.dzf.converter;

 import java.io.IOException;
import java.nio.charset.Charset; import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils; import com.alibaba.fastjson.JSONObject;
import com.dzf.vo.ResultInfo;
/**
* 自定义消息转换器
* @author dingzf
* @date 2018年1月20日
* @time 19:26:39
*/
public class MyMessageConverter extends AbstractHttpMessageConverter<ResultInfo> { public MyMessageConverter(){
super(Charset.forName("utf-8"),new MediaType("application","x-result"));//application/x-result 自己定义的媒体数据类型
} //所映射的model
@Override
protected boolean supports(Class<?> clazz) {
return ResultInfo.class.isAssignableFrom(clazz);
} @Override
protected ResultInfo readInternal(Class<? extends ResultInfo> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
String copyToString = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("utf-8"));//传输为json类型的数据
ResultInfo result = (ResultInfo)JSONObject.parse(copyToString);//转换为自己想要的数据类型 按需编写
return result;
} @Override
protected void writeInternal(ResultInfo t, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
String str = t.getCode()+"-"+t.getDesc();//返回到前台的数据
outputMessage.getBody().write(str.getBytes());
} }

二、在springmvc的配置文件中加入我们自定义的消息转换器

 <!--
打开springmvc的注解模式
mvc 请求映射 处理器与适配器配置 -->
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter" ><!--字符串转换器-->
<property name = "supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /><!--json转换器-->
<bean class ="com.dzf.converter.MyMessageConverter"> <!--自己定义的消息转换器-->
<property name = "supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>application/x-result;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

三、在前台指定发送数据的格式

 function test6(){
$.ajax({
type:'post',
url:'json/test6',
contentType:'application/x-result',
data:{code:"200",desc:"我是丁振锋"},
success:function(text){
alert(text);
},
error:function(data){
alert("后台异常!")
},
asyn:false,
cache:false
});
}

四、服务器端指定返回的数据格式

 /**
* 测试自定义消息转换器
* 在请求头上必须加上produces="application/x-result;charset=utf-8"
* @param request
* @param response
* @return
*/
@RequestMapping(value="/test6",produces="application/x-result;charset=utf-8")
@ResponseBody
public ResultInfo test6(HttpServletRequest request,HttpServletResponse response){
ResultInfo result = new ResultInfo();
result.setCode("200");
result.setDesc("请求成功!");
Map<String,String> map = new HashMap<String,String>();
map.put("name", "红霞");
map.put("age","22");
result.setData(map);
return result;
}

到这里,基本上就结束了!

注意点:

1.请求头的contentType必须要设值你自定义的数据格式

2.返回数据格式如果需要使用你自定义的数据格式,加上路由设置。即:produces="application/x-result;charset=utf-8"

springmvc-自定义消息转换器的更多相关文章

  1. springmvc 类型转换器 自定义类型转换器

    自定义类型转换器的步骤: 1.定义类型转换器 2.类型转换器的注册(在springmvc配置文件处理) 来解决多种日期格式的问题: springmvc 类型转换器 表单数据填错后返回表单页面(接上面的 ...

  2. JavaEE开发之SpringMVC中的自定义消息转换器与文件上传

    上篇博客我们详细的聊了<JavaEE开发之SpringMVC中的静态资源映射及服务器推送技术>,本篇博客依然是JavaEE开发中的内容,我们就来聊一下SpringMVC中的自定义消息转发器 ...

  3. SpringMVC类型转换器、属性编辑器

    对于MVC框架,参数绑定一直觉得是很神奇很方便的一个东西,在参数绑定的过程中利用了属性编辑器.类型转换器 参数绑定流程 参数绑定:把请求中的数据,转化成指定类型的对象,交给处理请求的方法 请求进入到D ...

  4. SpringMVC——消息转换器HttpMessageConverter(转)

    文章转自http://blog.csdn.net/cq1982/article/details/44101293 概述 在SpringMVC中,可以使用@RequestBody和@ResponseBo ...

  5. SpringBoot添加自定义消息转换器

    首先我们需要明白一个概念:springboot中很多配置都是使用了条件注解进行判断一个配置或者引入的类是否在容器中存在,如果存在会如何,如果不存在会如何. 也就是说,有些配置会在springboot中 ...

  6. springboot自定义消息转换器HttpMessageConverter

    在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换,底层这种灵活的消息转换机制就是利用HttpMessageCo ...

  7. springmvc 类型转换器 数据回显及提示信息

    处理器的写法: 类型转换器的写法: 类型转换器在springmvc.xml中的配置如下: index.jsp的写法:

  8. springmvc 日期转换器

    package com.xxx.common.controller.converter; import org.joda.time.DateTime; import org.joda.time.for ...

  9. Spring MVC自定义消息转换器(可解决Long类型数据传入前端精度丢失的问题)

    1.前言 对于Long 类型的数据,如果我们在Controller层通过@ResponseBody将返回数据自动转换成json时,不做任何处理,而直接传给前端的话,在Long长度大于17位时会出现精度 ...

  10. springboot自定义消息转换器HttpMessageConverter Spring Boot - 使用Gson替换Jackson

    Jackson一直是springframework默认的json库,从4.1开始,springframework支持通过配置GsonHttpMessageConverter的方式使用Gson. 在典型 ...

随机推荐

  1. 【python-opencv】几何变换

    """几何变换-缩放""" img = cv.imread(r'pictures\family.jpg') ""&quo ...

  2. CentOS安装Jdk并配置环境变量

    环境 CentOS7.2 (安装镜像CentOS-7-x86_64-DVD-1611) 目标 在CentOS7.2上安装jdk1.8(tar.gz安装包),并配置环境变量 jdk安装在/home/so ...

  3. java 泛型没有协变类型, 所以要重用extends, 但使用List<? extends Fruit> 可以是ArrayList<Fruit>()、ArrayList<Apple>()、ArrayList<Orange>(), 因此不能add元素进去

    class Fruit{} class Apple extends Fruit{} class SubApple extends Apple{} class Orange extends Fruit{ ...

  4. CentOS工作内容(六)双网卡带宽绑定bind teaming

    CentOS工作内容(六)双网卡带宽绑定bind  teaming Teaming功能是什么功能http://zhidao.baidu.com/link?url=cpcwl9LH4FSHJBaTW-e ...

  5. LVS + Keepalived 实现高可用、负载均衡 Web 集群

    简介: LVS 是 Linux Virtual Server 的简写,Linux 虚拟服务器的意思,是一个虚拟的服务器集群系统,此项目由章文嵩博士于 1998 年 5 月成立,是中国最早出现的自由软件 ...

  6. 删除排序数组中的重复数字 II

    题目连接 http://www.lintcode.com/zh-cn/problem/remove-duplicates-from-sorted-array-ii/ 题目大意 跟进“删除重复数字”: ...

  7. mysql5.7服务器The innodb_system data file 'ibdata1' must be writable导致无法启动服务器

    现象如下:The innodb_system data file 'ibdata1' must be writable. 解决方案如下: 1.关闭mysqld进程: 2.删除配置文件中datadir所 ...

  8. app加密算法

    php端 <?phpnamespace app\controllers;use yii\web\Controller;class TestController extends Controlle ...

  9. android实操--练习2

    练习2是实现一个计算器的功能:可以加减乘除:可以倒退,可以清空文本. 下面是效果展示: -----------------------布局------------------------------- ...

  10. Linux命令: 编辑模式移动光标

    敲命令按以下顺序 ①vim filename ②e ③i ④ESC 移动光标 0 (零):将光标移动到行的起始处. $:将光标移动到行的末尾处. H:将光标移到当前窗口(而非全文)的第一行起始处. M ...