views:

182

answers:

1

Hi,

I'm using java servlets and jsp in my application and I need to read the remote XML file and properly render it into HTML and display on a web page...What is the technology used for reading process?Should I use HTTPURLConnection class to read the contents of the xml file or there is some other way? And also,if I use servlet as a controller and JSP as a view,what would be the responsibility of servlet and jsp in this process?Should servlet just read the whole XML file and then just pass the read output to JSP which will just print it and render properly using XSL for example?

I really hope to hear from any people who may help,

With kind regards

+3  A: 

JSP has no responsibility here. Just transform the XML in servlet using XSL and write its result directly to the OutputStream of the response.

StreamSource xml = new StreamSource(new URL("http://external.com/file.xml").openStream());
StreamSource xsl = new StreamSource(new File("/path/to/file.xsl"));
StreamResult out = new StreamResult(response.getOutputStream());

try {
    Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
    transformer.transform(xml, out);
} catch (TransformerException e) {
    throw new ServletException("Transforming XML failed.", e);
}

Don't forget to set the Content-Type using HttpServletResponse#setContentType(), else the webbrowser may handle it as plaintext.

BalusC
Thanks so much for your reply! Just have a follow-up question: what if I want to display the outputed HTML in a specific part of a JSP page,but I want to do all the processing stuff in the servlet so there is no any business logic in the JSP..Can I follow the same method you described and then just use request.getRequestDispatcher("").forward() method to forward the presentation of data to the JSP where my formatted XML data will be presented along with the information I've got in JSP itself? I hope my question was clear:) Thx in advance
Alex
Just use `<jsp:include>` where the URL points to this servlet.
BalusC