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


相关推荐

  • error LNK2019: 无法解析的外部符号_error lnk2019无法解析的外部符号

    error LNK2019: 无法解析的外部符号_error lnk2019无法解析的外部符号废话不多说,直接上错误图片原本是生成一个静态链接库,然后在主函数中进行库函数的调用,编写静态库时,没存在此问题,在主函数中一调用就报错。添加库连接,附加依赖项——也无法彻底解决此问题。原来是从VisualStudio2010开始,VisualStudio要求项目到项目引用。如果你的项目没有项目到项目引用,那么你可能收到此链接器错误。添加项目到项目引用以修复此错误。…

    2022年9月28日
    0
  • 四十一、SPSS中的t检验和卡方检验[通俗易懂]

    四十一、SPSS中的t检验和卡方检验[通俗易懂]@Author:ByRunsen@Date:2020/5/14在2020年一月初,也是我大三上的寒假,我开始写书,为什么呢?因为化工原理和化工热力学挂了,我需要重拾自己的自信。对于一个大学三年,每天往死里干的人,竟然挂了两科。虽然,我化工专业已经陷入了绝境,大学我主要学习日语,Python,Java和一系列数据分析软件。所以本专栏数据分析将使用Excel,Powerbi,Python,R,Sql,SPSS,stata以及Tableau,后面还会补充BI。第五章应该是二月份完成的。文章目

    2022年5月16日
    91
  • 数据库导入sql文件_mysql导入sql文件命令

    数据库导入sql文件_mysql导入sql文件命令Sql文件导入数据库-保姆级教程,铁打的保姆,希望对大家能有所帮助,不要忘了点赞+收藏哦

    2022年10月2日
    0
  • python二级考试考生必看[通俗易懂]

    python二级考试考生必看[通俗易懂]考试环境:Windows7操作系统,Python3.5版本。已经预装idle开发环境(没有pycharm、spyder)涉及到考试中需要使用的库,无需考生安装,已经安装调试完毕,考试全程采用物理断网,

    2022年7月5日
    37
  • apache struts 2 任意代码执行漏洞

    apache struts 2 任意代码执行漏洞漏洞检测地址:http://0day.websaas.cn漏洞利用工具,如下:漏洞利用,如下:step1step2step3提权思路,如下:1、开启虚拟终端,执行命令,但是,提示“连接被

    2022年7月3日
    26
  • translate和paraphrase的区别_conversation dialogue

    translate和paraphrase的区别_conversation dialogueTranslateMessage(&msg);TranslateMessage是用来把快捷键消息转换为字符消息,并将转换后的新消息投递到调用线程的消息队列中。由于Windows对所有键盘编码都是采用虚拟键的定义,这样当按键按下时,并不得字符消息,需要键盘映射转换为字符的消息。字符消息被投递到调用线程的消息队列中,当下一次调用GetMessage函数时被取出。…

    2022年9月13日
    0

发表回复

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

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