How to manually render Spring MVC view to html?

Try autowiring the ViewResolver then calling resolveViewName("myview", Locale.US) to get the View.

Then call render() on the view, passing it a “mock” HTTP response that has a ByteArrayOutputStream for its output, and get the HTML from the ByteArrayOutputStream.

Update

Here’s the working example, copied from the question. (so the code is actually with the answer)

View resolvedView = thiz.viewResolver.resolveViewName("myViewName", Locale.US);
MockHttpServletResponse mockResp = new MockHttpServletResponse();
resolvedView.render(model.asMap(), req, mockResp);
System.out.println("rendered html : " + mockResp.getContentAsString());

Leave a Comment