示例ResponseBodyAdvice :
@Order(1)
@ControllerAdvice
public class EncryptBodyAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return returnType.getMethod().isAnnotationPresent(EncryptBody.class);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if(body==null) return null;
EncryptBodyMethod encryptBodyMethod;
if(returnType.getMethod().isAnnotationPresent(EncryptBody.class)){
EncryptBody encryptBody = returnType.getMethodAnnotation(EncryptBody.class);
encryptBodyMethod = encryptBody.value();
}
response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
String s = JSON.toJSONString(body);
return "3232312";
}
}
另外配置ConverterConfig也没有用:
@Configuration
public class HttpConverterConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(new LinkedList<MediaType>(){{
add(MediaType.TEXT_HTML);
add(MediaType.APPLICATION_JSON_UTF8);
}});
converters.add(new StringHttpMessageConverter());
converters.add(converter);
}
}
无论怎么样,返回的结果都是
"3232312"
像上面这样带个双引号,除非将控制器的返回值改成String就不会有了,请问有什么办法解决吗?
1 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
已解决,重写MappingJackson2HttpMessageConverter
的writeInternal
方法即可,完整配置如下:
@Configuration
public class HttpConverterConfig extends WebMvcConfigurerAdapter {
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
return new MappingJackson2HttpMessageConverter(){
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
if(object instanceof String){
Charset charset = this.getDefaultCharset();
StreamUtils.copy((String)object, charset, outputMessage.getBody());
}else{
super.writeInternal(object, type, outputMessage);
}
}
};
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = mappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(new LinkedList<MediaType>(){{
add(MediaType.TEXT_HTML);
add(MediaType.APPLICATION_JSON_UTF8);
}});
converters.add(new StringHttpMessageConverter());
converters.add(converter);
}
}
添加回答
举报
0/150
提交
取消