我有一种情况,我必须生成大量的HTML,然后将其作为字符串JSONP样式返回。所以最终的HTTP响应实际上就是这样的javascript文本:
myglobaljavascriptcallbackfunction('
< HTML here> ');
由于HTML很复杂,构建它的唯一合理方法是使用JSP。所以我想做的是获取JSP的HTML输出并将其传递给servlet,然后servlet可以使用必要的javascript包装HTML。
以下是我迄今为止最好的猜测。没有运气 - 来自Servlet的HTTP响应是myglobaljavascriptcallbackfunction('');
,没有任何JSP的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());
}
答案 0 :(得分:3)
如果您想在JSP中包含 Servlet响应,请使用<jsp:include>
。
如果要在Servlet中包含 JSP响应,请使用RequestDispatcher#include()
。这个就是你想要的。但是,您只需要将XHR请求URL更改为指向Servlet而不是JSP。
注意:getBytes()
调用存在潜在的字符编码问题,该调用隐式使用平台默认字符编码。