本文介绍了Spring MVC - 包含呈现的 JSP 视图的 AJAX-JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的控制器返回一个包含更新的 HTML 代码的 AJAX JSON 响应.

I need my controller to return an AJAX JSON response that contains the updated HTML code.

更新后的 HTML 代码是通过呈现 JSP 视图创建的.

The updated HTML code is created by rendering a JSP view.

例如:JSP:

<tr>
<td>${data1}</td>
<td>${data2}</td>
</tr>

JSON 响应:

{"columns" : "2", "rows":"1", "data":rendered view}

目前我正在尝试使用我自己的"输出流创建一个虚拟响应,并将渲染的视图内容放入 json 响应中,但没有成功.

Currently I'm trying to create a dummy response with "my own" outputstream and put the rendered view content in the json response, but with no luck.

除了我无法让这个解决方案发挥作用之外,感觉不太对.有关正确操作方法的任何提示?

Other than the fact I can't get this solution to work, it doesn't feel right.Any tips on the proper way to do it?

谢谢,奥利

推荐答案

如果要捕获的视图在 /WEB-INF/views/my.jsp 中,则调用

If the view you want to capture is in /WEB-INF/views/my.jsp, then call

request.getRequestDispatcher("/WEB-INF/views/my.jsp").include(request, myResponse);

其中 myResponse 是您创建的 HttpServletResponseWrapper 或 Spring MockHttpServletResponse.在后一种情况下,您可以从 getContentAsString() 获取渲染输出.

where myResponse is either a HttpServletResponseWrapper that you've created, or a Spring MockHttpServletResponse. In the latter case you can get the rendered output from getContentAsString().

在下面编辑

我遇到了另一个关于捕获 servlet 响应的 SO 问题有一些指向您可以使用的 HttpServletResponseWrappers 的指针.

I ran into another SO question around capturing servlet responses that had some pointers to HttpServletResponseWrappers that you can use.

两个看起来不错的实现:

Two implementations that look good:

  1. DWR SwallowingHttpServletResponse
  2. Sitemesh PageResponseWrapper

享受,

这篇关于Spring MVC - 包含呈现的 JSP 视图的 AJAX-JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 17:29