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

ber*_*tie 26 java spring spring-mvc

是否可以在我的控制器映射方法中将我的视图渲染为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";
}
Run Code Online (Sandbox Code Playgroud)

我期待的是:

@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;
}
Run Code Online (Sandbox Code Playgroud)

我想知道在控制器方法中手动创建视图和手动渲染视图的正确方法是什么.

---------更新---------

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

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());
Run Code Online (Sandbox Code Playgroud)

Ted*_*ham 21

尝试自动装配ViewResolver,然后调用resolveViewName("myview", Locale.US)以获取View.

然后调用render()视图,向其传递一个"模拟"HTTP响应,其响应具有ByteArrayOutputStream,并从ByteArrayOutputStream获取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());
Run Code Online (Sandbox Code Playgroud)