Spring MVC - AJAX-JSON Response to contain rendere

2019-02-16 01:43发布

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

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

For example: JSP:

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

JSON response:

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

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?

Thanks, Ori

1条回答
Melony?
2楼-- · 2019-02-16 02:35

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);    

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().

EDIT below

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

Enjoy,

查看更多
登录 后发表回答