1

How can I get content of a jsp page, after servlet made a forward. At them moment I'm trying the following:

request.getRequestDispatcher(DESTINATION_PAGE).forward(request, response);
URL teamsURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + DESTINATION_PAGE);
URLConnection teamsCon = teamsURL.openConnection();
String fileName = request.getServletContext().getRealPath("/") + System.currentTimeMillis() + ".html";
System.out.println(fileName);
try (BufferedReader in = new BufferedReader(new InputStreamReader(teamsCon.getInputStream()));
     PrintWriter out = new PrintWriter(fileName)) {
    String inputLine = null;
    while ((inputLine = in.readLine()) != null) {
        out.println(inputLine);
    }
}

I get the html with empty divs. But, I want the same page I see in browser.

Sorry for messy post, ask for what info you need, I'll update my post accordingly.

hooknc
  • 4,854
  • 5
  • 31
  • 60
Azaro
  • 35
  • 1
  • 1
  • 9

1 Answers1

2

If you're trying to get the response body after you've written it, you'll need to use a custom HttpServletResponse wrapper that keeps track of what was written to the OutputStream directly or with the Writer.

You will do this in a servlet Filter after chain.doFilter(request, yourResponseWrapper) returns. A simple example can be found here.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Thanks, but is there a way to map this filter to a jsp which is called via forward? Or do i have to move all my logic from a servlet to a filter? – Azaro Oct 03 '13 at 18:41
  • @Azaro You can setup your filter to only work on forwards. I would suggest you mix that with a `url-pattern` that matches your `Servlet`'s. – Sotirios Delimanolis Oct 03 '13 at 18:42
  • Can u link me an example of filter that works on forward? Cant find it. – Azaro Oct 03 '13 at 19:04
  • @Azaro Take a look at some other answers, like [here](http://stackoverflow.com/questions/5325405/how-is-it-possible-that-filter-is-applied-when-its-dispatcher-is-forward-as-well). – Sotirios Delimanolis Oct 03 '13 at 19:07
  • Last question, so the part in the filter after chain.doFilter() is called after servlet? I made forward in servlet(returns blank html page, but file is full) and then redirect in filter to the created file, is that a right approach? – Azaro Oct 03 '13 at 19:29
  • @azaro Yes, `chain.doFilter` will execute the `Servlet` down the line. If you do a `forward`, I THINK that you will reenter the `Filter` body. – Sotirios Delimanolis Oct 03 '13 at 19:32
  • Thanks man, i would love to +1 you, but i dont have enough rep. – Azaro Oct 03 '13 at 19:36