首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将SpringMVC视图手动呈现为html?

如何将SpringMVC视图手动呈现为html?

提问于 2018-02-06 09:38:31
回答 3关注 0查看 843

是否可以在控制器映射方法中将视图呈现为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());

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

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