I am trying to output the rendering of a JSP page using RequestDispatcher.include() in the following method:
public static String readTemplate(HttpServletRequest request, HttpServletResponse response, String template) {
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response) {
private final StringWriter sw = new StringWriter();
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(sw);
}
@Override
public String toString() {
return sw.toString();
}
};
String templateFile = "/templates/" + template + ".jsp";
logger.log(Level.INFO, "Reading template {0} ...", templateFile);
try {
request.getRequestDispatcher(templateFile).include(request, responseWrapper);
} catch (ServletException | IOException | IllegalStateException e) {
logger.log(Level.SEVERE, e.getMessage());
}
logger.log(Level.INFO, "Completed reading template {0}", templateFile);
// retrieve HTML from response
return responseWrapper.toString();
}
The method is part of a servlet I am running with Tomcat8. This works perfectly the first time, but hangs at the include call the second run (i.e. if I click refresh on the browser).
I have already verified the dispatcher is not null.
This is what I can see from the catalina.log (cleaned for your review)
First run:
26-Feb-2015 17:41:17.921 INFO [http-nio-8081-exec-2] ism.Reports.readTemplate Reading template /templates/INCIDENT_REPORT.jsp ...
26-Feb-2015 17:41:18.046 INFO [http-nio-8081-exec-2] ism.Reports.readTemplate Completed reading template /templates/INCIDENT_REPORT.jsp
Second run (response never returns, i.e. browser always loading page):
26-Feb-2015 17:41:26.327 INFO [http-nio-8081-exec-8] ism.Reports.readTemplate Reading template /templates/INCIDENT_REPORT.jsp ...
This does not change until I reboot Tomcat.
Can someone explain what am I doing wrong or at least how to debug this? Thanks!
EDIT 1: Forgot to say the method is static, but I also tried making it not static didn't make any difference