I want to replace exisiting json response(In some condition) with the new one using filters. What am trying to do is read existing response (JSON) from filter. Modify it with new values and write back to response. But the result shows both the response.
That is , what i have read from response and what i added newly. But i need to replace the old response with new. Code added below.
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();
}