如何从Spring中的HTTPServletResponse对象获取HTML作为字符串?

时间:2013-08-21 19:09:37

标签: java spring spring-mvc jsonp

我想从控制器获取已处理JSP的HTML内容。我正在使用Tiles Implementation for Views。

在我的场景中,我想从jsp生成HTML并将其作为JSONP发送。

所以我需要掌握来自控制器的Generated html。

3 个答案:

答案 0 :(得分:2)

你走了!

这对我来说很完美:

@Service
public class CustomViewProcessor
{
    private static Logger m_log = LoggerFactory.getLogger(CustomViewProcessor.class);

    @Autowired
    @Qualifier("tilesViewResolver")
    private ViewResolver viewResolver;

    @Autowired
    @Qualifier("commonInterceptor")
    CommonInterceptor commonInterceptor;

    public String renderView(HttpServletRequest request, Model model, String viewName)
    {
        ModelAndView mav = new ModelAndView();
        mav.addAllObjects(model.asMap());
        mav.setViewName(viewName);
        commonInterceptor.updateRequest(mav, request);
        try
        {
            View view = viewResolver.resolveViewName(mav.getViewName(), request.getLocale());
            HttpServletResponse localResponse = new MyHttpServletResponseWrapper(new MockHttpServletResponse());

            view.render(mav.getModel(), request, localResponse);

            return localResponse.toString();
        }
        catch (Exception e)
        {
            return "";
        }
    }

    public boolean doesViewExist(HttpServletRequest request, String viewName)
    {
        try
        {
            if (viewResolver.resolveViewName(viewName, request.getLocale()) != null)
            {
                return true;
            }
        }
        catch (Exception e)
        {
            m_log.error(e.getMessage(), e);
        }

        return false;
    }

    static class MyHttpServletResponseWrapper extends HttpServletResponseWrapper
    {
        private StringWriter sw = new StringWriter();

        public MyHttpServletResponseWrapper(HttpServletResponse response)
        {
            super(response);
        }

        public PrintWriter getWriter() throws IOException
        {
            return new PrintWriter(sw);
        }

        public ServletOutputStream getOutputStream() throws IOException
        {
            throw new UnsupportedOperationException();
        }

        public String toString()
        {
            return sw.toString();
        }
    }
}

答案 1 :(得分:0)

您需要使用@ResponseBody注释您的控制器方法。请查看文档以获取更多详细信息

答案 2 :(得分:0)

控制流离开DispatcherServlet并在填充JSP页面模板之前移动到Servlet容器(例如Tomcat)。所以Spring MVC永远不会看到从JSP模板生成的最终HTML。

如果要将最终的HTML输出传递给JSONP请求,则必须将其作为Servlet容器中的过滤器实现,这可能支持也可能不支持该行为。