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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Ubuntu LAMP 虚拟域名配置

    Ubuntu LAMP 虚拟域名配置虚拟域名配置

    2022年6月1日
    29
  • Nginx报错:Sorry, the page you are looking for is currently unavailable. Please try again later.

    Nginx报错:Sorry, the page you are looking for is currently unavailable. Please try again later.

    2021年10月28日
    197
  • 如何运行SpringBoot项目

    如何运行SpringBoot项目最近在Ecplise上面写了一个简单的SpringBoot的测试项目,SpringBoot里面是有主函数的:我们知道的是在Ecplise上面找到这个主函数然后runas-&gt;javaApplication就可以了但是总不能一直不脱离Ecplise,总要出来自己单练的第一步:我就新建的一个文件夹boottest,然后右键导出整个工程:导出的是jar包,然后我们看…

    2022年10月13日
    2
  • 国产CPU架构、国产Linux操作系统及其国产数据库等关键应用

    国产CPU架构、国产Linux操作系统及其国产数据库等关键应用关于国产CPU架构及Linux变种编译器1、CPU架构3大阵营整合为两大CPU阵营:处理器架构_百度百科CPU架构是CPU厂商给属于同一系列的CPU产品定的一个规范,主要目的是为了区分不同类型CPU的重要标示。市面上的CPU分类主要分有两大阵营,一个是intel、AMD为首的复杂指令集CPU,另一个是以IBM、ARM为首的精简指令集CPU。两个不同品牌的CPU,其产品的架构也不相同,例如,Intel、AMD的CPU是X86架构的,而IBM公司的CPU是PowerPC架构,AR…

    2022年5月13日
    114
  • .pyd是什么文件_python解析html

    .pyd是什么文件_python解析html有的时候,为了对python文件进行加密,会把python模块编译成.pyd文件,供其他人调用。拿到一个.pyd文件,在没有文档说明的情况下,可以试试查看模块内的一些函数和类的用法。首先importXXX(pyd的文件名)然后直接print(dir(XXX))print(help(xxx))其中dir()列出了属性和方法而hlep()直接列出了其中的函数以及参数,并且是源码的函数名和类型,…

    2025年7月25日
    2
  • Junit单元测试教程_单元测试调试react源码

    Junit单元测试教程_单元测试调试react源码如果你只会使用@Test来完成单元测试,那你是时候该深入一下了,其实知识点一点都不少!

    2022年10月10日
    2

发表回复

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

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