6

What's the easiest way to make a JSP page render, then get the rendered html content as a string?

user802232
  • 2,541
  • 7
  • 34
  • 40
  • possible duplicate of [Capture generated dynamic content at server side](http://stackoverflow.com/questions/1963158/capture-generated-dynamic-content-at-server-side) – BalusC Nov 15 '11 at 11:46

3 Answers3

10

There is this tutorial, which explains every step with code:

http://valotas.com/get-output-of-jsp-or-servlet-response/

Doing it this way has advantages when the JSP is not accessible by URL directly.

Slapy
  • 317
  • 3
  • 9
barfuin
  • 16,865
  • 10
  • 85
  • 132
  • 1
    In addition you might want to override setContentType(String x) in the from the example. Otherwise forward() might change it for your servlet's response. – Twilite Dec 07 '12 at 14:59
3

You should provide your own wrapper for the Writer of HttpServletResponse (via HttpServletResponseWrapper in a Filter), and each time you write to that writer, also store in a StringBuilder.

That's just a sketch of the code, there is a sufficient number of examples, but the main steps are:

  • create a filter
  • wrap PrintWriter to make it store each write in a builder
  • extend HttpServletResponseWrapper and make it return the writer wrapper
  • create chain.doFilter(request, new HttpServletResponseWrapper(response))
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

Use java.net.URL and java.net.URLConnection class methods or JSTL <c:import/>

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186