springboot实战第四章-自定义HttpMessageConverter

springboot实战第四章-自定义HttpMessageConverter

自定义HttpMessageConverter

  HttpMessageConverter是用来处理request和response里的数据的。Spring内置了很多HttpMessageConverter,比如MappingJackson2HttpMessageConverter,StringHttpMessageConverter等。

  本章实现自定义的HttpMessageConverter,很简单。

1.自定义HttpMessageConverter

package com.just.springmvc4.messageconverter;

import com.just.springmvc4.domain.DemoObj;
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;

public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {
    /**
     * 定义字符编码,防止乱码
     */
    private static final Charset DEFAULT_CHARSET=Charset.forName("UTF-8");
    /**
     * 新建自定义的媒体类型
     */
    public MyMessageConverter(){
        super(new MediaType("application","x-wisely",DEFAULT_CHARSET));
    }

    /**
     * 表明只处理DemoObj这个类
     */
    @Override
    protected boolean supports(Class<?> aClass) {
        return DemoObj.class.isAssignableFrom(aClass);
    }

    /**
     * 重写readInternal方法,处理请求的数据
     */
    @Override
    protected DemoObj readInternal(Class<? extends DemoObj> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String temp=StreamUtils.copyToString(httpInputMessage.getBody(),DEFAULT_CHARSET);
        String[] tempArr=temp.split("-");
        return new DemoObj(new Long(tempArr[0]),tempArr[1]);
    }

    /**
     * 重写writeInternal,处理如何输出数据到response
     */
    @Override
    protected void writeInternal(DemoObj demoObj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String out="hello: "+demoObj.getId()+"-"+demoObj.getName();
        StreamUtils.copy(out, DEFAULT_CHARSET, httpOutputMessage.getBody());
    }
}

在本实例中我进行了编码的处理,为了防止中文乱码,输入输出的编码格式统一为UTF-8

2.配置文件MyMvcConfig中添加自定义的HttpMessageConverter

/**
     * 添加自定义的httpMessageConverter
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(messageConverter());
    }

    @Bean
    public MyMessageConverter messageConverter(){
        return new MyMessageConverter();
    }

3.控制器

package com.just.springmvc4.controller;

import com.just.springmvc4.domain.DemoObj;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConverterController {
    @RequestMapping(value = "/converter",produces = "application/x-wisely")
    public DemoObj converter(@RequestBody DemoObj demoObj){
         return demoObj;
    }
}

produces指定返回自定义的媒体类型

4.自定义的jsp页面以及ViewController里的配置

converter.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>converter测试</title>
</head>
<body>
   <div id="resp"></div>
<input type="button" value="请求" onclick="req()">

<script src="../assets/js/jquery-3.3.1.min.js" type="text/javascript"></script>
<script>
    function req() {
        $.ajax(
            {
                url:"converter",
                data:"1000-goodluck",
                type:"POST",
                contentType:"application/x-wisely",
                success:function (data) {
                    $("#resp").html(data);
                }
            }
        )
    }
</script>
</body>
</html>

ViewController配置:

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/toUpload").setViewName("upload");
        registry.addViewController("/toConverter").setViewName("converter");
    }

5.结果演示:

springboot实战第四章-自定义HttpMessageConverter

//TODO:本实例只是自定义的HttpMessageConverter,在实际场景中可能有全局的处理,比如要全局请求与返回都要是Json格式,这个等有空了尝试下。

书接上文,既然这个HttpMessageConverter这么牛逼,这次来个全局的处理,输入和输出都自动转成json。

实现这个功能需要两样东西,第一个是pom文件中加入jackson的jar包,第二个是在配置文件中加入MappingJackson2HttpMessageConverter

pom.xml:

springboot实战第四章-自定义HttpMessageConverter

配置文件MyMvcConfig添加:

springboot实战第四章-自定义HttpMessageConverter

controller测试,直接返回一个map:

springboot实战第四章-自定义HttpMessageConverter

实验结果:

springboot实战第四章-自定义HttpMessageConverter

good work.

项目地址:https://gitee.com/yuanhan93/springmvc4Learning

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100311.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • CausalDiscoveryToolbox:因果建模、因果图代码实现

    CausalDiscoveryToolbox:因果建模、因果图代码实现Cdt工具包实现了端到端的因果建模方法,支持从观测数据中恢复直接依赖关系(因果图的骨架)和变量之间的因果关系。基于python实现了许多用于图结构恢复的算法,接口简单,易于上手。

    2022年8月14日
    7
  • 网络传真机

    网络传真机网络传真机有两个种类:1、软件传真机。适合于小型的企业。2、硬件传真机。适合于大中型企业和单位组织。传真机的评价标准:1、稳定性。指时间长后的反映、占用资源情况、是否能处理大量的传真。2、适用性。传真机的其他的功能的选择:邮件收发传真、传真审批、传真鉴章、传真编辑、短信通知、语音功能、集团内部免费传真等。3、兼容性。传真服务器是否可以…

    2022年6月28日
    25
  • 如何搭建ELK日志分析系统

    如何搭建ELK日志分析系统文章目录简介 1 项目拓扑图与项目环境 1 1 项目拓扑图 1 2 项目环境 2 部署 ELK 日志分析系统 2 1 项目需求 2 2 部署流程 2 2 1 配置环境 2 2 2 部署 elasticsearc 2 3 安装 elasticsearc head 插件简介 ELKStack 是 Elasticsearc Logstash Kiban 三个开源软件的组合 在实时数据检索和分析场合 三者通常是配合共用 而且又都先后归于 Elastic co 公司名下 1 项目拓扑图与项目环境 1 1 项目拓扑图 1 2 项

    2025年7月6日
    2
  • VMware安装win10反复出现 BootManager,vmware无法安装win10,无法引导

    VMware安装win10反复出现 BootManager,vmware无法安装win10,无法引导VMwareworkstation分为pro版本和player版本,电脑一直用VMwareworkstationplayer,轻便免费很不错,但是今天准备安装win10系统,竟安装不上,反复出现BootManager。以为是软件版本的问题,从vmware15升级到16问题仍然存在。经过查询别人通过修改固件类型为bios可以解决这个问题(40条消息)vmware安装win10镜像出现bootManager_☆☆★☆☆的博客-CSDN博客但是我的版本是VMwareworkst

    2022年6月18日
    173
  • vue 富文本插件_前端富文本编辑器插件

    vue 富文本插件_前端富文本编辑器插件1.引用quill&lt;scriptsrc="/lib/quill/quill.min.js"&gt;&lt;/script&gt;&lt;linkhref="/lib/quill/quill.snow.css"rel="stylesheet"/&gt;2.RichEditorDemo.vue&lt;template&gt;&lt;divcl

    2022年10月14日
    3
  • sdio接口是什么_如何理解api接口

    sdio接口是什么_如何理解api接口运用SD卡第一步,认识SDIO接口做毕业设计需要用到大量的音频文件,一般的存储器满足不了存储要求,故选择SD卡作为存储器件。在这里记录一下自己的学习经历,学习一个新的IC,无非是要么根据时序图写出Read和Write函数,要么是根据通信总线和IC相关操作指令去完成Read和Write函数。只有能与对应IC“说话”,我们才能去开发它更多地可能性。这里以原子探索者为例,为大家介绍一下SD卡相关知识。…

    2022年10月3日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号