如何执行从Javascript到JSP的Ajax调用? [英] How to perform Ajax call from Javascript to JSP?

查看:411
本文介绍了如何执行从Javascript到JSP的Ajax调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JavaScript from which I am making an Ajax Call to a JSP. Both JavaScript and JSP are deployed in the same web server. From JSP I am forwarding the request to one of the service (servlet) available in other web server using HttpURLConnection. I got the response in JSP, but now I need to pass the response back to JavaScript which made an Ajax Call. How I can do it?

我的最终目标是从JavaScript向JSP发出Ajax请求,然后从该JSP向服务之一发出Ajax请求,并将响应返回给JavaScript.

My ultimate goal is to make an Ajax request from JavaScript to a JSP and from that JSP to one of the services and return the response back to JavaScript.

推荐答案

JSP是 URLConnection#getInputStream() HttpServletResponse#getOutputStream() 常用的Java IO方法.

JSP is the wrong tool for the job. The output would be corrupted with template text. Replace it by a Servlet. You just need to stream URLConnection#getInputStream() to HttpServletResponse#getOutputStream() the usual Java IO way.

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

仅此而已.在web.xml中将这个servlet映射到某个url-pattern上,然后让您的ajax东西调用该servlet URL.

That's all. Map this servlet in web.xml on a certain url-pattern and have your ajax stuff call that servlet URL instead.

这篇关于如何执行从Javascript到JSP的Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆