Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the rendered output of a Spring 3.1 MVC View

I am needing to the get the rendered output of Spring 3.1 MVC View into a String (for sending to a PDF converter, or to a MIME email, etc...) and I have been using the following code:

This is injected into the Controller

    @Autowired
    TilesViewResolver viewResolver;

And the following helper method:

    private String renderViewToString(ModelMap map, HttpServletRequest request, HttpServletResponse httpServletResponse, final String viewName) {
        final StringWriter html = new StringWriter();
        View pdfView = new View() {
            @Override
            public String getContentType() {
                return "application/pdf";
            }

            @Override
            public void render(Map<String, ?> model, 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);
                Map<String, Object> newModel = new HashMap<String, Object>(model);
                newModel.put("pdfMode", Boolean.TRUE);
                realView.render(newModel, request, wrapper);
            }
        };
        try {
            pdfView.render(map, request, httpServletResponse);
        } catch (Exception e) {
            // Ignored for now
        }
        return html.toString();
    }

Credit to Ted Young and his HTML2PDFViewResolver from which my code is based on.

My Question is there a better way to do this? The code I have works fine but now I am getting close to Production and I thought that if there is room for improvement I would like to try it.

Thanks to all

like image 686
Ninju Bohra Avatar asked Feb 29 '12 15:02

Ninju Bohra


1 Answers

You are breaking the MVC pattern by clubbing together the view and controller. A better solution is to define a view and register it to ContentNegotiatingViewResolver. Based on the content type requested the resolver would delegate the request to your view.

e.g.

    <bean
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="0" />
        <property name="mediaTypes">
            <map>
                <entry key="pdf" value="application/pdf" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="com.abc.MyCustomView">
                    <property name="contentType" value="pdf" />
                </bean>
            </list>
        </property>
    </bean>
like image 168
praveenj Avatar answered Oct 24 '22 02:10

praveenj