spring 有很多自定义的消息转换器,今天我们来介绍下spring自定义消息转换器,
一 、使用场景
前端接收到的数据需要处理下才可以正确的映射到javabean
二 、缺点
需要重新定义消息头contentType
三、使用方法
1、继承 AbstractHttpMessageConverter<T>, 重写接收与响应参数过程中的消息转换逻辑
public class ParamConvert extends AbstractHttpMessageConverter<Test> { public ParamConvert() { // 新建一个我们自定义的媒体类型application/xxx-junlin super(new MediaType("application", "xxx-test", Charset.forName("UTF-8"))); } @Override protected boolean supports(Class aClass) { return true; } @Override protected Test readInternal(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException { String temp = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8")); JSONObject req = JSONObject.parseObject(temp); JSONObject busiInfo = req.getJSONObject("busiInfo"); Test po = new Test(); po.setAuthor("dd"); return po; } @Override protected void writeInternal(Test t, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException { t.setCopyRight("测试") String out = JSONObject.toJSONString(t); httpOutputMessage.getBody().write(out.getBytes()); }
2、添加到spring的转换器中
继承WebMvcConfigurationSupport
@Configuration public class WebConfig extends WebMvcConfigurationSupport{
@Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(converter()); } @Bean public ParamConvert converter() {
ParamConvert paramConver = new ParamConvert(); List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(new MediaType("application", "xxx-junlin", Charset.forName("UTF-8"))); paramConver.setSupportedMediaTypes(fastMediaTypes);
return paramConver;
}
}
3、在controller中定义
@RequestMapping(value="test", method= RequestMethod.POST) @ResponseBody public JSONObject test(@RequestBody Test test){ JSONObject response = new JSONObject(); response.put("rescode","drgdfg"); return response; }
目前test无需前端设置就会有一个固定的anthor属性