【问题标题】:How to perform Ajax call from Javascript to JSP?如何执行从 Javascript 到 JSP 的 Ajax 调用?
【发布时间】:2011-03-31 05:32:27
【问题描述】:

我有一个 JavaScript,我正在从中对 JSP 进行 Ajax 调用。 JavaScript 和 JSP 都部署在同一个 Web 服务器中。从 JSP 中,我使用 HttpURLConnection 将请求转发到其他 Web 服务器中可用的服务(servlet)之一。我在 JSP 中得到了响应,但现在我需要将响应传递回进行 Ajax 调用的 JavaScript。我该怎么做?

我的最终目标是从 JavaScript 向 JSP 发出 Ajax 请求,从该 JSP 向其中一项服务发出 Ajax 请求,并将响应返回给 JavaScript。

【问题讨论】:

  • 返回 html、xml 还是 json?如果是 json 或 xml,不要使用 jsp 的!为此有 servlet。如果是html,考虑用json代替=P

标签: javascript ajax jsp servlets


【解决方案1】:

JSP 是工作的wrong tool。输出将被模板文本损坏。将其替换为 Servlet。你只需要用通常的 Java IO 方式将URLConnection#getInputStream() 流式传输到HttpServletResponse#getOutputStream()

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    URLConnection connection = new URL("http://other.service.com").openConnection();
    // Set necessary connection headers, parameters, etc here.

    InputStream input = connection.getInputStream();
    OutputStream output = response.getOutputStream();
    // Set necessary response headers (content type, character encoding, etc) here.

    byte[] buffer = new byte[10240];
    for (int length = 0; (length = input.read(buffer)) > 0;) {
        output.write(buffer, 0, length);
    }
}

就是这样。将此 servlet 映射到某个 url-pattern 上的 web.xml,并让您的 ajax 东西调用该 servlet URL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多