Tip: how to write an XML document with JSP for AJAX applications

AJAX applications usually connect to a server side application and request data in the form of XML. When the server side is written in JSP (Java Server Pages), for example a spring-framework web application with JSP views, writing the XML response is sometimes problematic.

The problem:

When using JSP to format the data in to XML and send it to the AJAX application, the XML is not recognized as XML (empty DOM object) and the AJAX application does not function properly.

The solution:

Add this to the beginning of the JSP
<%

response.setContentType(“text/xml”);
response.setHeader(“Cache-Control”, “no-cache”);
response.setHeader(“pragma”,”no-cache”);

%>

In addition, make sure there are no spaces between this addition and the root tag of the XML in the JSP, these spaces might create the same problem.

An example of this AJAX-JSP communication can be found in the Spring-dashboard code under the examples folder in this release (files: monitorData.jsp and monitor.jsp)

Another issue you might face with AJAX is client side caching. You can read more about this and how to solve this issue in this article – Solving the browser caching problem of AJAX applications

Leave a Reply