tags:

views:

181

answers:

3

Hi There,

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.

+1  A: 

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

deamon
+2  A: 
  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)
Bozho
+2  A: 

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: http://stackoverflow.com/questions/1963158/capture-generated-dynamic-content-at-server-side/1963571#1963571

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

BalusC
What do you mean by 'idempotent'? Also do I need to use the full address in URL or can I just use 'URL("/xml/generate.jsp")' ?
Mazzi
idempotent = always the same result when invoking a procedure. In HTTP terms, that's how GET works. Sending one URL always give the same result. This isn't the case in POST, because the input/output is not controlled by only the URL. And yes, you of course need the full address. It would otherwise not know where to find it. You can however construct it dynamically based on the methods provided by `HttpServletRequest`.
BalusC
Thanks mate, it seems like it answered my question. Although I haven't been able to write it to the file so I wouldn't know if it actually read the data from the InputStream.Thanks again.
Mazzi
You can find basic Java IO tutorial here: http://java.sun.com/docs/books/tutorial/essential/io/ It isn't that hard, just a `while` loop with a `byte[]` buffer inside a `try-catch-finally` block which reads the inputstream into the buffer and writes the buffer to the outputstream until end of inputstream is reached.
BalusC
Yes, I am abale to create the file easily, the issue is just the path issue I have created a new topic (http://stackoverflow.com/questions/2046265/trying-to-update-the-file-in-src-web-prod-folder-jsp) For some reason I am not able to create the file in the place I want to. Cheers
Mazzi