J Jarrett,
You have a few options here, but they are all kind of cumbersome.
- as Bear Bibeault suggested, you can access your JSP by its URL; the downside here is that you will be accessing the page as a completely foreign resource, so you won't be able to pass your data as a
Java object, but only as request parameters;
- much of the complexity of what you are trying to achieve arises from the fact that a servlet's output is firmly tied to the socket connection. There is a way though to outsmart the container: wrap the response object into your own class that implements HttpServletResponse by simply delegating every method call to the underlying original response object - except one method, getWriter(). To make this job easier there is a class provided on the Servlet API, HttpServletResponseWrapper that does exactly that. All you need to do is override the getWriter() method (and provide a way to get the resulting string back into the invoking servlet):
public class JspResponseWrapper extends HttpServletResponseWrapper {
private StringWriter stringWriter;
private PrintWriter printWriter;
public JspResponseWrapper(HttpServletResponse response) {
super(response);
stringWriter = new StringWriter();
printWriter = new PrintWriter(stringWriter);
}
public PrintWriter getWriter() {
return printWriter;
}
public String getText() {
return stringWriter.getBuffer().toString();
}
}
Then in the servlet's doGet() method you go like:
request.setAttribute("data-object", dataObject);
JspResponseWrapper responseWrapper = new JspResponseWrapper(response);
getServletContext().getRequestDispatcher("dynamicXml.jsp").include(request, responseWrapper);
String yourXml = responseWrapper.getText();
- but you will be infinitely better off [whispering very quietly] if you stop using JSP and switch to template-based rendering that uses a template engine like Velocity (
http://jakarta.apache.org/velocity/). With Velocity, for example, solving your problem would take literally just one line of code, but there are lots of other, more important benefits that are mainly of the architectural nature. If you are curious as to what I am talking about, you can check out the link in my signature.