Mazzi
Mazzi

Reputation: 949

How to save content of a page call into a file in jsp/java?

In jsp/java how can you call a page that outputs a xml file as a result and save its result (xml type) into a xml file on server. Both files (the file that produces the xml and the file that we want to save/overwrite) live on the same server.

Basically I want to update my test.xml every now and then by calling generate.jsp that outputs a xml type result.

Thank you.

Upvotes: 1

Views: 1689

Answers (3)

BalusC
BalusC

Reputation: 1108642

If the request is idempotent, then just use java.net.URL to get an InputStream of the JSP output. E.g.

InputStream input = new URL("http://example.com/context/page.jsp").openStream();

If the request is not idempotent, then you need to replace the PrintWriter of the response with a custom implementation which copies the output into some buffer/builder. I've posted a code example here before: Capture generated dynamic content at server side

Once having the output, just write it to disk the usual java.io way, assuming that JSP's are already in XHTML format.

Upvotes: 2

Bozho
Bozho

Reputation: 597046

  1. Register a filter that adds a wrapper to your response. That is, it returns to the chain a new HttpServletResponse objects, extending the original HttpServletResponse, and returning your custom OutputStream and PrintWriter instead of the original ones.
  2. Your OutputStream and PrintWriter calls the original OutputStream and PrintWriter, but also write to a your file (using a new FileOutputStream)

Upvotes: 2

deamon
deamon

Reputation: 92387

Why don't you use a real template engine like FreeMarker? That would be easier.

Upvotes: 1

Related Questions