views:

33

answers:

1

I have a situation where I have to generate a lot of HTML and then return it as a string JSONP style. So the eventual HTTP response will actually be javascript text like this:

myglobaljavascriptcallbackfunction('<HTML here>');

Since the HTML is complex, the only sane way to construct it is with a JSP. So what I would like to do is take the HTML output of the JSP and pipe it to a servlet which can then wrap the HTML with the necessary javascript.

Below is my best guess so far. No luck - the HTTP response from the Servlet is myglobaljavascriptcallbackfunction(''); without any of the JSP's HTML.

JSP


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="/MyServlet" />
<div>
   <span>Imagine some really complicated stuff here</span>
<div>

Servlet

protected void doGet(...) {

    String pre = "myglobaljavascriptcallbackfunction('";
    String post = "');";

    OutputStream out = response.getOutputStream();
    out.write(pre.getBytes());

    // transfer request to response
    InputStream in = request.getInputStream();
    byte[] buf = new byte[1024]; 
    int count = 0; 
    while ((count = in.read(buf)) > 0) { 
        out.write(buf, 0, count);
        // TODO: escape single quote chars
    }

    out.write(post.getBytes());
}
+2  A: 

Use <jsp:include> if you want to include Servlet response in JSP.

Use RequestDispatcher#include() if you want to include JSP response in Servlet. This one is what you want. You should however only need to change the XHR request URL to point to the Servlet instead of the JSP.


Note: you have a potential character encoding problem with the getBytes() call which is implicitly using the platform default character encoding.

BalusC
This is closer, but it immediately dumps the HTML to the ServletResponse. I need to be able to process the output of the JSP before it is written to the Response to remove white space and escape certain characters since the HTML will all be put into a javascript string (btw I'm using JSONP here not XHR)
Robert
Use a `Filter` with a whitespace trimeer or a `File` or `URLConnection` in servlet to open JSP locally. Read "XHR" as "Client". Source of request actually doesn't matter. I was just expecting JS/ajax (XHR).
BalusC