springboot實戰第四章-自定義HttpMessageConverter
阿新 • • 發佈:2019-01-03
自定義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.配置檔案中新增自定義的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.結果演示:
//TODO:本例項只是自定義的HttpMessageConverter,在實際場景中可能有全域性的處理,比如要全域性請求與返回都要是Json格式,這個等有空了嘗試下。
書接上文,既然這個HttpMessageConverter這麼牛逼,這次來個全域性的處理,輸入和輸出都自動轉成json。
實現這個功能需要兩樣東西,第一個是pom檔案中加入jackson的jar包,第二個是在配置檔案中加入MappingJackson2HttpMessageConverter
pom.xml:
配置檔案:
controller測試,直接返回一個map:
實驗結果:
good work.