Last active
August 29, 2015 14:08
-
-
Save dlundy/fc4a3bc83240fcef921d to your computer and use it in GitHub Desktop.
A Spring controller that can render views to a string (useful for PDF generation, for instance)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class StringRenderableController | |
{ | |
@Autowired | |
ViewResolver viewResolver; | |
protected String renderViewToString(Model model, HttpServletRequest request, HttpServletResponse httpServletResponse, final String viewName) | |
{ | |
final StringWriter html = new StringWriter(); | |
View renderView = new View() | |
{ | |
@Override | |
public String getContentType() { | |
return "text/html"; | |
} | |
@Override | |
public void render(Map<String, ?> modelMap, HttpServletRequest request, HttpServletResponse response) throws Exception | |
{ | |
HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response) | |
{ | |
@Override | |
public PrintWriter getWriter() throws IOException { | |
return new PrintWriter(html); | |
} | |
}; | |
View realView = viewResolver.resolveViewName(viewName, Locale.US); | |
realView.render(modelMap, request, wrapper); | |
} | |
}; | |
try | |
{ | |
renderView.render(model.asMap(), request, httpServletResponse); | |
} | |
catch (Exception e) | |
{ | |
throw new Exception("Error rendering view: " + e); | |
} | |
return html.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment