但行好事  莫问前程

SpringMvc4.x高级配置(二):自定义HttpMessageConverter

一. 点睛

消息转换器HttpMessageConverter是用来处理requestresponse里面的数据的。Spring为我们内置了大量的HttpMessageConverter,例如,MappingJackson2HttpMessageConverter,StringHttpMessageConverter等。下面演示自定义的HttpMessageConverter,并注册这个HttpMessageConverterSpring MVC

二. 示例

1. 自定义HttpMessageConverter

package org.light4j.springMvc4.messageconverter;

import java.io.IOException;
import java.nio.charset.Charset;

import org.light4j.springMvc4.domain.DemoObj;
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> {//①

    public MyMessageConverter() {
        super(new MediaType("application", "x-longjiazuo",Charset.forName("UTF-8")));//②
    }

    /**
     * ③
     */

    @Override
    protected DemoObj readInternal(Class<? extends DemoObj> clazz,
            HttpInputMessage inputMessage) throws IOException,
            HttpMessageNotReadableException {
        String temp = StreamUtils.copyToString(inputMessage.getBody(),

        Charset.forName("UTF-8"));
        String[] tempArr = temp.split("-");
        return new DemoObj(new Long(tempArr[0]), tempArr[1]);
    }

    /**
     * ④
     */
    @Override
    protected boolean supports(Class<?> clazz) {
        return DemoObj.class.isAssignableFrom(clazz);
    }

    /**
     * ⑤
     */
    @Override
    protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        String out = "hello:" + obj.getId() + "-"+ obj.getName();
        outputMessage.getBody().write(out.getBytes());
    }
}

代码解释:

① 继承AbstractHttpMessageConverter接口来实现自定义的HttpMessageConverter
② 新建一个我们自定义的媒体类型application/x-longjiazuo
③ 重写readInternal方法,处理请求的数据。代码表明我们处理由”-“隔开的数据,并转成DemoObj的对象。
④ 表明本HttpMessageConverter只处理DemoObj这个类。
⑤ 重写writeInternal方法,处理如何输出数据到response。此例中,我们在原样输出前面加上"hello:"

2. 配置

在文件MyMvcConfig的方法addViewControllers中添加viewController映射访问演示页面converter.jsp,代码如下:

registry.addViewController("/converter").setViewName("/converter");

添加完成之后的代码如下所示:

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

配置自定义的HttpMessageConverterBean,在Spring MVC里面注册HttpMessageConverter有两个方法:

1. 在文件MyMvcConfig中配置configureMessageConverters:重载会覆盖掉Spring MVC默认注册的多个HttpMessageConverter
2. 在文件MyMvcConfig中配置extendMessageConverters:仅添加一个自定义的HttpMessageConverter,不覆盖默认注册的HttpMessageConverter

所以,在此例中我们重写extendMessageConverters,在文件MyMvcConfig中增加下面的代码:

@Override
 public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(converter());
}

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

3. 演示控制器

package org.light4j.springMvc4.web;

import org.light4j.springMvc4.domain.DemoObj;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ConverterController {

    @RequestMapping(value = "/convert", produces = { "application/x-longjiazuo" }) //①
    public @ResponseBody DemoObj convert(@RequestBody DemoObj demoObj) {

        return demoObj;
    }
}

代码解释:

① 指定返回的媒体类型为我们自定义的媒体类型application/x-longjiazuo

4. 演示页面

src/main/resources下新建conventer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HttpMessageConverter Demo</title>
</head>
<body>
    <div id="resp"></div><input type="button" onclick="req();" value="请求"/>
<script src="assets/js/jquery.js" type="text/javascript"></script>
<script>
    function req(){
        $.ajax({
            url: "convert",
            data: "1-longjiazuo", //①
            type:"POST",
            contentType:"application/x-longjiazuo", //②
            success: function(data){
                $("#resp").html(data);
            }
        });
    }

</script>
</body>
</html>

代码解释:

① 注意这里的数据格式,后台处理按此格式处理,用”-“隔开。
contentType设置的媒体类型是我们自定义的application/x-longjiazuo

5. 运行

访问http://localhost/springMvc4.x-httpMessageConverter/converter如下图所示:

单击”请求”按钮,做如下观察。请求类型如下图所示:
xxx
后台获得我们自定义的数据格式,如下图所示:
xxx
页面效果如下图所示:

三. 源代码示例:

github地址:点击查看
码云地址:点击查看

打赏
欢迎关注人生设计师的微信公众账号
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » SpringMvc4.x高级配置(二):自定义HttpMessageConverter

分享到:更多 ()

人生设计师-接受不同的声音

联系我关于我