springboot实战第四章-自定义HttpMessageConverter

2021-05-19 16:34:10 浏览数 (1)

自定义HttpMessageConverter

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

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

1.自定义HttpMessageConverter

代码语言:javascript复制
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

代码语言:javascript复制
/**
     * 添加自定义的httpMessageConverter
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(messageConverter());
    }

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

3.控制器

代码语言:javascript复制
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:

代码语言:javascript复制
<%@ 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配置:

代码语言:javascript复制
@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/toUpload").setViewName("upload");
        registry.addViewController("/toConverter").setViewName("converter");
    }

5.结果演示:

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

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

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

pom.xml:

配置文件MyMvcConfig添加:

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

实验结果:

good work.

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

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

0 人点赞