#ResponseFilter.py #A Response Filter to Capture and Modify the Response from javax import servlet from javax.servlet import http from java.lang import * from java.io import * import string , sys #Buffer contains the stand-in stream response generated by the target servlet or HTML buffer = None #Class Wrapper Extends Standard HttpServletResponseWrapper class Wrapper(http.HttpServletResponseWrapper): #Override the default toString method to capture the #target servlet or HTML Response def toString(self): global buffer return buffer.toString() #Override the Standard getWriter method #to have the response contents in a stand-in stream defined below def getWriter (self): global buffer buffer = StringWriter() return PrintWriter(buffer) class ResponseFilter (servlet.Filter): def doFilter(self, req, res,chain): #Capture the Stream which writes response to the client toclient = res.getWriter() #Create the Wrapper object with its default constructor wrapper_stream = Wrapper(res) #Pass this Wrapper object to get the response from the target #Servlet or HTML by overriding the getWriter method chain.doFilter(req,wrapper_stream) #Get the Wrapped Response if (str(wrapper_stream.getContentType()) == "text/html"): #If response is HTML, set ContentType of Client Response to HTML res.setContentType("text/html") #Get the Response data in a string wrapped_response = str(wrapper_stream.toString()) #Find the occurrence of end HTML tag in the response if wrapped_response.find("") <> -1: #Append a message to this response wrapped_response = wrapped_response[:wrapped_response.rfind("")] + """

This Response was Monitored by the Filter
""" + wrapped_response[wrapped_response.rfind(""):] #Send the Modified response to the client toclient.println(wrapped_response) else: #If the end tag is wrapped_response = wrapped_response[:wrapped_response.rfind("")] + """

This Response was Monitored by the Filter
""" + wrapped_response[wrapped_response.rfind(""):] #write the modified response toclient.println(wrapped_response) #Deallocate the buffer buffer = None def init(self, config): print "Response Filter Initialized" def destroy(self): print "Response Filter Destroyed" sys.exit(0)