kobi
kobi

Reputation: 322

How to return rendered jsp view (html) as json field?

I want to do async pagination, i.e. browser makes Ajax call to Spring controller that would return json consisting of control data for pagination (current page, number of total pages) and field containing html with content. Is it possible to render html from jsp view and put it in json response as one of the fields?

Upvotes: 1

Views: 259

Answers (2)

Aquarelle
Aquarelle

Reputation: 9138

Yes, actually, it is possible to do this, and I've been doing this for many years. It's a bit tricky, but the idea is to swallow the rendered response into a string buffer and then put the contents of the string buffer into the JSON response. I unfortunately cannot put the entire answer here, since it's a lot of code. You may PM me for the code, or else try to figure it out on your own with the following pointers.

Do a Google search for 'SwallowingHttpServletResponse' from the Direct Web Remoting project. This class subclasses HttpServletResponse and writes the rendered JSP template to an internal buffer instead of to the servlet's normal output stream.

First, you get an instance of a RequestDispatcher (HttpServletRequest.getRequestDispatcher()), and call its include() method, handing it an instance of a SwallowingHttpServletResponse that was passed a StringWriter instance. The call to include() invokes the JspServlet and gets it to render the JSP. After the call to include() completes, the rendered JSP content will be inside of the aforementioned StringWriter. You can then call getBuffer().toString() on the StringWriter to get the resultant HTML and place it into a JSON structure.

In total, you will need 3 classes: SwallowingHttpServletResponse, WriterOutputStream (which subclasses ServletOutputStream), and InternalJSPRenderer (which implements Spring's ServletContextAware). The latter two you will need to write yourself, and the first one will need its import statements replaced (replace javax.servlet with jakarta.servlet).

Upvotes: 0

Uladzislau Kaminski
Uladzislau Kaminski

Reputation: 2255

Take a look at MVC flow:

enter image description here

As you see, the JSP generation will be done by View Template and the ready HTML will be returned to the browser by Front Controller (Dispatcher Servlet in Spring).

That is why it is not possible to add Html as a part of the JSON response.

Actually JSP is not the best solution for SPA applications and async page reloading.

Upvotes: 1

Related Questions