0

I use Spring MVC. I want to render some jsp by forwarding to it. And then I want to write the result to json.

For exmple I want to render my complex jsp and on exit I want to get: {"result":"ok","html":"......."}

How can I do this? I've tried to look at request.getRequestDispatcher("tutorMini").forward(request, response) But if I can't pass response to it, bcz it should write all output to it.

And I've tried to use some json tags in jsp, but it has some troubles with hierarchy: HTML output with jsp:include and json-taglib

Community
  • 1
  • 1
AKonst
  • 51
  • 1
  • 6

1 Answers1

0

Since you need to apply additional conversion when inserting HTML into JSON (escape ' and "), you cannot write output of your JSP to the response directly.

So, you need to create an instance of ServletResponseWrapper that would save the output (by overriding getWriter() and/or getOutputStream()) and pass it to RequestDispatcher.include() (it looks more appropriate than forward() for this case):

MyServletResponseWrapper wrapper = new MyServletResponseWrapper(response);
request.getRequestDispatcher("tutorMini").include(request, wrapper);
String html = wrapper.getSavedOutput();

Then you can insert the saved content into JSON, escaping it appropriately.

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • And what should I write in MyServletResponseWrapper? Is there any fake implementation of it? – AKonst Jan 19 '13 at 18:04
  • See http://stackoverflow.com/questions/701681/how-can-i-read-an-httpservletreponses-output-stream – axtavt Jan 19 '13 at 18:23