简体   繁体   English

如何链接JSP对Servlet请求的响应

[英]How to chain JSP response to Servlet request

I have a situation where I have to generate a lot of HTML and then return it as a string JSONP style. 我遇到的情况是必须生成大量HTML,然后将其作为字符串JSONP样式返回。 So the eventual HTTP response will actually be javascript text like this: 因此,最终的HTTP响应实际上将是如下所示的javascript文本:

myglobaljavascriptcallbackfunction(' <HTML here> '); myglobaljavascriptcallbackfunction(' <HTML here> ');

Since the HTML is complex, the only sane way to construct it is with a JSP. 由于HTML很复杂,所以构造它的唯一明智的方法是使用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. 因此,我想做的是获取JSP的HTML输出并将其通过管道传输到servlet,然后可以使用必要的javascript包装HTML。

Below is my best guess so far. 到目前为止,这是我最好的猜测。 No luck - the HTTP response from the Servlet is myglobaljavascriptcallbackfunction(''); 运气不好-来自Servlet的HTTP响应是myglobaljavascriptcallbackfunction(''); without any of the JSP's HTML. 没有任何JSP的HTML。

JSP 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 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());
}

Use <jsp:include> if you want to include Servlet response in JSP. 如果要在JSP中包括 Servlet响应,请使用<jsp:include>

Use RequestDispatcher#include() if you want to include JSP response in Servlet. 如果要在Servlet中包含 JSP响应,请使用RequestDispatcher#include() 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. 但是,您只需要更改XHR请求URL即可指向Servlet而不是JSP。


Note: you have a potential character encoding problem with the getBytes() call which is implicitly using the platform default character encoding. 注意: getBytes()调用存在潜在的字符编码问题,该调用隐式使用平台默认字符编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM