本文主要是介绍自定义HttpMessageConverter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
HttpMessageConverter是用来处理request和response里的数据的,我们可以自定义,用于类型转换。
自定义对象和字符串之间的转换:
public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {public MyMessageConverter(){//设置我们新定义的媒体类型为application/x-wisely super(new MediaType("application","x-wisely", Charset.forName("UTF-8"))); }//标明本HttpMessageConverter只处理DemoObj这个类 @Override protected boolean supports(Class<?> aClass) {return DemoObj.class.isAssignableFrom(aClass); }//把中间用-隔开的数据转成DemoObj对象 @Override protected DemoObj readInternal(Class<? extends DemoObj> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {String temp= StreamUtils.copyToString(httpInputMessage.getBody(),Charset.forName("UTF-8")); String[] tempArr=temp.split("-"); return new DemoObj(new Long(tempArr[0]),tempArr[1]); }//把DemoObj对象转化成字符串并输出到response中 @Override protected void writeInternal(DemoObj obj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {String out="hello:"+obj.getId()+"-"+obj.getName(); httpOutputMessage.getBody().write(out.getBytes()); } }添加自定义converter:
@Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(converter()); }示例:
@Controller public class ConverterController {//接收字符串转化为对象,然后把对象又转化为字符串输出。 @RequestMapping(value="/convert",produces = {"application/x-wisely"})public @ResponseBody DemoObj convert(@RequestBody DemoObj demoObj){return demoObj; } }
<body> <div id="resp"></div><input type="button" οnclick="req();" value="请求"/> <script src="assets/js/jquery.js" type="text/javascript"></script> <script> function req() {$.ajax({url:"convert", data:"1-wangyunfei", type:"POST", contentType:"application/x-wisely", success:function (data) {$("#resp").html(data); }}); }</script> </body>
这篇关于自定义HttpMessageConverter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!