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

  • 回答 (3)
  • 关注 (0)
  • 查看 (77)

是否可以在控制器映射方法中将视图呈现为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());
Mr.CryptoMr.Crypto提问于
tthha真理偏执狂回答于
已采纳

尝试自动连接视图解析器,然后调用resolveViewName("myview", Locale.US)去看试图。

然后调用render()在视图上,传递给它一个“模拟”HTTP响应,它的输出有一个ByteArrayOutputStream,并从ByteArrayOutputStream获得HTML。

回答过的其他问题

关于作者

所属标签

扫码关注云+社区