Como processar manualmente o Spring MVC view para html?
É possível renderizar minha visualização em html no meu método de mapeamento de controlador, para que eu possa retornar o html renderizado como parte do meu objeto json?
Exemplo do meu método usual de controlador:
@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";
}
O que eu espero:
@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;
}
Gostaria de saber qual é a maneira correta de criar a visualização e renderizá-la em html manualmente, dentro do método do controlador.
--------- atualização ---------
Aqui está o exemplo de trabalho da orientação da resposta aceita:
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());