gpt4 book ai didi

java - 如何手动将 Spring MVC View 呈现为 html?

转载 作者:IT老高 更新时间:2023-10-28 13:46:56 25 4
gpt4 key购买 nike

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

我常用的 Controller 方法示例:

@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;
}

我想知道在 Controller 方法中手动创建 View 并将 View 渲染为 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());

最佳答案

尝试 Autowiring ViewResolver,然后调用 resolveViewName("myview", Locale.US) 来获取 View 。

然后在 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());

关于java - 如何手动将 Spring MVC View 呈现为 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22422411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com