开发者

How to perform Ajax call from Javascript to JSP?

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 respon开发者_如何学编程se in JSP, but now I need to pass the response back to JavaScript which made an Ajax Call. How I can do it?

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜