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

示例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就不会有了,请问有什么办法解决吗?

达令说
浏览 1617回答 1
1回答

MMTTMM

已解决,重写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); } }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java