首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何手动将Spring MVC视图渲染为html?

如何手动将Spring MVC视图渲染为html?
EN

Stack Overflow用户
提问于 2014-03-15 18:14:25
回答 3查看 24.5K关注 0票数 30

是否可以在控制器映射方法中将视图呈现为html,以便我可以将呈现的html作为json对象的一部分返回?

我常用的控制器方法示例:

@RequestMapping(value={"/accounts/{accountId}"}, method=RequestMethod.GET)
public String viewAcc(final HttpServletRequest req, 
        final HttpServletResponse resp, final Model model,
        @PathVariable("accountId") final String docId) {

    // do usual processing ...

    // return only a STRING value, 
    //   which will be used by spring MVC to resolve into myview.jsp or myview.ftl
    //   and populate the model to the template to result in html
    return "myview";
}

我期望的是:

@RequestMapping(value={"/accounts/{accountId}"}, method=RequestMethod.GET)
public String viewAcc(final HttpServletRequest req, 
        final HttpServletResponse resp, final Model model,
        @PathVariable("accountId") final String docId) {

    // do usual processing ...

    // manually create the view
    ModelAndView view = ... ? (how)

    // translate the view to the html
    //   and get the rendered html from the view
    String renderedHtml = view.render .. ? (how)

    // create a json containing the html
    String jsonString = "{ 'html' : " + escapeForJson(renderedHtml) + "}"

    try {
        out = response.getWriter();
        out.write(jsonString);
    } catch (IOException e) {
        // handle the exception somehow
    }

    return null;
}

我想知道在控制器方法中手动创建视图并将视图呈现为html的正确方法是什么。

更新

以下是可接受答案的指导中的工作示例:

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());
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22422411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档