如何获取HttpServletResponse里面的内容

如何获取HttpServletResponse里面的内容,第1张

背景:在SPRING 框架之中, 有一个服务端需要提供多种形态的服务,这里的多种形态只是返回值得展示形式(其实 数据内在逻辑完全一样), 比如:

形式1: JSONP({“key1”: value1, "key2":value2, "key3":value3, })

形式2: {“key1”: value1, "key2":value2, "key3":value3, }

为了使得后台业务处理代码一样(不做任何区分),现在理由过滤器,对返回接口进行处理,根据需要加上 :JSONP()

主要实现步骤如下:

1 在webxml 中配置过滤器

<filter>

<filter-name>RewriteResponse</filter-name>

<filter-class>comrobinfilterRewriteResponse</filter-class>

</filter>

<filter-mapping>

<filter-name>RewriteResponse</filter-name>

<servlet-name>/</servlet-name>

</filter-mapping>

// 斜杠星代表匹配任何请求

2 重点在于RewriteResponse 过滤器

public class RewriteResponseFilter extends Filter {

public String description() {

// TODO Auto-generated method stub

return null;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException {

// TODO Auto-generated method stub

ResponseWrapper responseWrapper = new ResponseWrapper((>

import javaioStringWriter;

import javautilHashMap;

import javautilList;

import javautilMap;

import orgcodehausjacksonJsonFactory;

import orgcodehausjacksonJsonGenerator;

import orgcodehausjacksonJsonParserFeature;

import orgcodehausjacksonmapJsonSerializer;

import orgcodehausjacksonmapObjectMapper;

import orgcodehausjacksonmapSerializationConfigFeature;

import orgcodehausjacksontypeTypeReference;

public class JsonUtils

{

private static ObjectMapper mapper = null;

static { mapper = new ObjectMapper();

mapperconfigure(SerializationConfigFeatureFAIL_ON_EMPTY_BEANS, false);

mapperconfigure(JsonParserFeatureALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);

}

public static String toJson(Object target)

{

String json = "";

try {

StringWriter sw = new StringWriter();

JsonGenerator gen = new JsonFactory()createJsonGenerator(sw);

mapperwriteValue(gen, target);

genclose();

json = swtoString();

}

catch (Exception e) {

throw new UnexpectedException("对象转换Json字符串出错," + targettoString(), e);

}

return json;

}

}

经过各种方式 ,最后使用这种方式

jackson配置成

objectMappersetSerializationInclusion(IncludeNON_EMPTY);

空的 null的不序列化 ,这样前端可以在实体上赋值默认值 ,如果是对象就new出来 ,这样取就不会有空指针错误了

还可以减少网络上的传输 ,缩小了json中没用的字段

加快了gson解析速度 ,因为对象变小了加快解析速度

看起来也很清晰了 ,如果很多空字段看起来很多 很杂乱

就这种方式了

以上就是关于如何获取HttpServletResponse里面的内容全部的内容,包括:如何获取HttpServletResponse里面的内容、springnvc怎么传递数组、咨询一下数据库里通过SQL结构化查询出的表数据记录怎么转换为JSON格式等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9515322.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-29
下一篇2023-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存