0

I m trying to use aspectJ to intercept HttpServlet.do*(request, response) and get the HTML text ( need to extract the title and maybe store the html to a file).

What is the best way to access the response body (html text) once I have a reference to the HttpServletResponse?

Here is my staring code.

public aspect HttpRequestHandlerAspect {

pointcut getRequest(HttpServletRequest request, HttpServletResponse response) 
    : execution(protected * javax.servlet.http.HttpServlet.*(HttpServletRequest, HttpServletResponse))  
    && args(request, response);

  Object around(HttpServletRequest request, HttpServletResponse response) : getRequest(request, response) {
      Object ret = proceed(request, response);
              // now how do I access the HTML response text ( and get the title of the page) in here?

    }
}
Sammy
  • 4,538
  • 8
  • 33
  • 52

1 Answers1

1

This might not be the precise answer for your question, but try extracting the response as suggested here: How can I read an HttpServletReponses output stream? You don't have to create a filter, only an HttpServletResponseWrapper which you pass to

proceed(request, wrapper).

Object around(HttpServletRequest request, HttpServletResponse response): getRequest(request, response) {
    MyHttpServletResponseWrapper wrapper = new MyHttpServletResponseWrapper(response);
    Object ret = proceed(request, wrapper);
    // The MyHttpServletReponseWrapper class captures everything and doesn't forward to the original stream, so we have to do this
    response.getWriter().write(wrapper.toString());
    // use wrapper.toString() to access response
}
Community
  • 1
  • 1
Katona
  • 4,816
  • 23
  • 27
  • Thanks for the answer, while this works fine to get the html text, it doesn't render the response to the browser anymore. I want to get the response HTML without the user feeling the difference. – Sammy Aug 05 '13 at 22:47
  • @Sammy: indeed, the wrapper class returns its own `PrintWriter` and it doesn't forward the writes to the `PrintWriter` of the wrapped response. I modified my answer which gives a workaround for this with writing the whole captured data after `proceed(request, wrapper)` has been called. Would be better to create a `TeePrintWriter` like [this](http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/TeeOutputStream.html). – Katona Aug 06 '13 at 06:47
  • @Sammy: You can find a `CopyPrintWriter` which actually does the capturing of writes but also delegates to the original one: http://stackoverflow.com/a/3242482/594406 – Katona Aug 06 '13 at 07:00