0
我想用新的过滤器替换现有的json
响应(在某些情况下)。我想要做的是从过滤器中读取现有响应(JSON
)。用新值修改它并回写回应。但结果显示了这两个答案。在春天使用新的servlet过滤器替换现有的响应mvc
也就是说,我从响应中读到了什么,以及我最近添加了什么。但我需要用新的替换旧的响应。下面添加代码。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
chain.doFilter(request,new HttpServletResponseWrapper((HttpServletResponse)response) {
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps)
);
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new DelegatingServletOutputStream (new TeeOutputStream(super.getOutputStream(), ps))
);
}
});
/* get existing response as string*/
String respopn=baos.toString();
JSONObject json=new JSONObject(respopn);
JSONObject dMap=new JSONObject(json.get("dataMap"));
dMap.put("new", "newValue");
json.put("dataMap", dMap); // Modified the old datamap with new json
JsonMapper jsonMap=new JsonMapper();
jsonMap.setJson(json);
String str=jsonMap.getJson();
byte[] responseToSend = restResponseBytes(jsonMap);
response.getOutputStream().write(responseToSend); // write to response only the new one
}
catch(Exception e)
{
e.printStackTrace();
}
}
private byte[] restResponseBytes(Object response) throws IOException {
String serialized = new ObjectMapper().writeValueAsString(response);
return serialized.getBytes();
}
可能重复:https://开头stackoverflow.com/questions/14736328/looking-for-an-example-for-inserting-content-into-the-response-using-a-servlet-f,https://stackoverflow.com/questions/34439260/replace- response-body-using-filter,https:// stackoverf low.com/questions/24452318/how-to-alter-the-body-of-a-http-response-in-a-filter – 2017-10-10 06:03:26