3

I am facing a problem, while encoding the response that I send back for an AJAX request, using GZIP. Can anyone give me some pointers on this please?

  1. There is an AJAX request from the JSP,
  2. An action class (Struts) at the server side handles the request,
  3. The response is prepared as a JSON object,
  4. The JSON string is written to the Response object and sent back,
  5. the JSON string is read from the responseText property of the xmlHttp object back at the jsp

This works fine. However, instead of sending the raw JSON data, if I send back encoded JSON data, then there are issues.

Server Side Code to create GZip'ed JSON :

// jsonStr = JSONObj.toString();  
ByteArrayOutputStream bos = new ByteArrayOutputStream();  
GZIPOutputStream gzip = new GZIPOutputStream(bos);  
gzip.write(jsonStr.getBytes());  
gzip.close();  
String newStr = new String(bos.toByteArray());  
// set the response header and send Encoded JSON response  
response.setHeader("Content-Type", "application/json");  
response.setHeader("Content-Encoding", "gzip");  
response.setHeader("Vary", "Accept-Encoding");  
pw = response.getWriter();  
pw.write(newStr);  
pw.close();

At the JSP :

// marker  
alert('Length of the received Response Text : ' + xmlHttp.responseText.length);
// evaluate the JSON  
jsonStr = eval('(' + xmlHttp.responseText + ')');

The alert box, on receiving the response, reports length as 0!

jmattheis
  • 10,494
  • 11
  • 46
  • 58
Rohitesh
  • 31
  • 1
  • 2
  • From where do you get the response? Did you try to write in responses output stream? – Trick Nov 17 '09 at 12:24
  • response is of type, HttpServletResponse response. It comes as a parameter to the function execute, in an org.apache.struts.action.Action sub class! I am using Struts. – Rohitesh Nov 18 '09 at 06:13
  • So your action classes implement ServletResponseAware? And did you try to write to responses output stream? – Trick Nov 18 '09 at 08:36
  • Umm, actually, I managed to solve it. It was a problem with the charset while forming the string. Will be posting the entire code soon. Hope that will help everyone in understanding what was going on. Thanks for your interest in solving this. – Rohitesh Nov 18 '09 at 09:48
  • Is the response so large that you have to GZIP it? I'm asking more out of curiosity, and because I'd like to know how you arrived at the conclusion that it needed GZIPping. – T9b May 05 '11 at 10:16

0 Answers0