为了账号安全,请及时绑定邮箱和手机立即绑定

使用ResponseBodyAdvice对响应体加密结果去掉双引号

使用ResponseBodyAdvice对响应体加密结果去掉双引号

达令说 2019-01-17 11:44:46
示例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个赞

已解决,重写MappingJackson2HttpMessageConverterwriteInternal方法即可,完整配置如下:

@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);
    }
}
查看完整回答
反对 回复 2019-02-12
  • 1 回答
  • 0 关注
  • 1616 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信