zoukankan      html  css  js  c++  java
  • springmvc-自定义消息转换器

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

    如有不对地方望指出!

    一、自定义类实现AbstractHttpMessageConverter

     1 package com.dzf.converter;
     2 
     3 import java.io.IOException;
     4 import java.nio.charset.Charset;
     5 
     6 import org.springframework.http.HttpInputMessage;
     7 import org.springframework.http.HttpOutputMessage;
     8 import org.springframework.http.MediaType;
     9 import org.springframework.http.converter.AbstractHttpMessageConverter;
    10 import org.springframework.http.converter.HttpMessageNotReadableException;
    11 import org.springframework.http.converter.HttpMessageNotWritableException;
    12 import org.springframework.util.StreamUtils;
    13 
    14 import com.alibaba.fastjson.JSONObject;
    15 import com.dzf.vo.ResultInfo;
    16 /**
    17  * 自定义消息转换器
    18  * @author dingzf
    19  * @date 2018年1月20日
    20  * @time 19:26:39
    21  */
    22 public class MyMessageConverter extends AbstractHttpMessageConverter<ResultInfo> {
    23 
    24         
    25     public MyMessageConverter(){
    26         super(Charset.forName("utf-8"),new MediaType("application","x-result"));//application/x-result 自己定义的媒体数据类型
    27     }
    28     
    29     //所映射的model
    30     @Override
    31     protected boolean supports(Class<?> clazz) {
    32         return ResultInfo.class.isAssignableFrom(clazz);
    33     }
    34 
    35     @Override
    36     protected ResultInfo readInternal(Class<? extends ResultInfo> clazz, HttpInputMessage inputMessage)
    37             throws IOException, HttpMessageNotReadableException {
    38         String copyToString = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("utf-8"));//传输为json类型的数据
    39         ResultInfo result = (ResultInfo)JSONObject.parse(copyToString);//转换为自己想要的数据类型  按需编写
    40         return result;
    41     }
    42 
    43     @Override
    44     protected void writeInternal(ResultInfo t, HttpOutputMessage outputMessage)
    45             throws IOException, HttpMessageNotWritableException {
    46         String str = t.getCode()+"-"+t.getDesc();//返回到前台的数据
    47         outputMessage.getBody().write(str.getBytes());
    48     }
    49 
    50 }

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

     1 <!-- 
     2         打开springmvc的注解模式
     3     mvc 请求映射 处理器与适配器配置 -->
     4     <mvc:annotation-driven >
     5         <mvc:message-converters register-defaults="true">
     6             <bean class="org.springframework.http.converter.StringHttpMessageConverter" ><!--字符串转换器-->
     7             <property name = "supportedMediaTypes">
     8                 <list>
     9                     <value>application/json;charset=utf-8</value>
    10                     <value>text/html;charset=utf-8</value>
    11                 </list>
    12             </property>
    13             </bean>
    14             <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /><!--json转换器-->
    15             <bean class ="com.dzf.converter.MyMessageConverter"> <!--自己定义的消息转换器-->
    16             <property name = "supportedMediaTypes">
    17                 <list>
    18                     <value>application/json;charset=utf-8</value>
    19                     <value>application/x-result;charset=utf-8</value>
    20                     <value>text/html;charset=utf-8</value>
    21                 </list>
    22             </property>
    23             </bean>
    24         </mvc:message-converters>
    25     </mvc:annotation-driven>

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

     1 function test6(){
     2     $.ajax({
     3         type:'post',
     4         url:'json/test6',
     5         contentType:'application/x-result',
     6         data:{code:"200",desc:"我是丁振锋"},
     7         success:function(text){
     8             alert(text);
     9         },
    10         error:function(data){
    11             alert("后台异常!")
    12         },
    13         asyn:false,
    14         cache:false
    15     });
    16 }

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

     1 /**
     2      * 测试自定义消息转换器
     3      * 在请求头上必须加上produces="application/x-result;charset=utf-8"
     4      * @param request
     5      * @param response
     6      * @return
     7      */
     8     @RequestMapping(value="/test6",produces="application/x-result;charset=utf-8")
     9     @ResponseBody
    10     public ResultInfo test6(HttpServletRequest request,HttpServletResponse response){
    11         ResultInfo result = new ResultInfo();
    12         result.setCode("200");
    13         result.setDesc("请求成功!");
    14         Map<String,String> map = new HashMap<String,String>();
    15         map.put("name", "红霞");
    16         map.put("age","22");
    17         result.setData(map);
    18         return result;
    19     }

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

    注意点:

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

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

  • 相关阅读:
    【C语言】学习笔记9——结构struct(2)
    WPF dev 获取gridControl筛选后的数据
    WPF DEV dxc:ChartControl 柱状图
    WPF 重写ListBox(透明效果)
    WPF 后台重写 DataTemplate
    WPF 去掉Drag a column header here to group by that column
    c# 对DataTable进行分组group by
    c# ref与out用法
    WPF canvas设置旋转角度和偏移位置
    WPF 流加载
  • 原文地址:https://www.cnblogs.com/zfding/p/8322382.html
Copyright © 2011-2022 走看看