获取Spring 3.1 MVC视图的渲染输出

时间:2012-02-29 15:21:01

标签: spring spring-mvc

我需要将Spring 3.1 MVC View的渲染输出转换为字符串(用于发送到PDF转换器,或发送到MIME电子邮件等等)并且我一直在使用以下代码:

将其注入Controller

    @Autowired
    TilesViewResolver viewResolver;

以下辅助方法:

    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();
    }

归功于我的代码所基于的Ted Young及其HTML2PDFViewResolver

我的问题是有更好的方法吗?我的代码工作正常,但现在我已接近Production,我认为如果有改进的余地,我想尝试一下。

感谢所有

1 个答案:

答案 0 :(得分:1)

您正在通过将视图和控制器聚合在一起来打破MVC模式。更好的解决方案是定义视图并将其注册到ContentNegotiatingViewResolver。根据请求的内容类型,解析器会将请求委托给您的视图。

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>