首先應創建自定義轉換器類,實現HttpMessageConverter<T>
接口:
package com.somepackage;
public class DirectionConverter implements HttpMessageConverter<Sort.Direction> {
public boolean canRead(Class<?> aClass, MediaType mediaType) {
return aClass== Sort.Direction.class;
}
public boolean canWrite(Class<?> aClass, MediaType mediaType) {
return false;
}
public List<MediaType> getSupportedMediaTypes() {
return new LinkedList<MediaType>();
}
public Sort.Direction read(Class<? extends Sort.Direction> aClass,
HttpInputMessage httpInputMessage)
throws IOException, HttpMessageNotReadableException {
String string = IOUtils.toString(httpInputMessage.getBody(), "UTF-8");
//here do any convertions and return result
}
public void write(Sort.Direction value, MediaType mediaType,
HttpOutputMessage httpOutputMessage)
throws IOException, HttpMessageNotWritableException {
}
}
我以前IOUtils
從Apache Commons IO爲轉換InputStream
到String
。但是你可以用任何首選的方式來完成。
現在你已經在Spring轉換器列表中註冊了創建的轉換器。添加到明年<mvc:annotation-driven>
標籤:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.somepackage.DirectionConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
或者,如果您使用的是Java的配置:
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
messageConverters.add(new DirectionConverter());
super.configureMessageConverters(converters);
}
}
能否請您POST請求消息的例子嗎? – chaoluo