0

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?

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.

srv
  • 435
  • 1
  • 5
  • 22
  • Returning html, xml or json? If json or xml, do NOT use jsp's! There are servlets for that. If html, consider using json instead =P – BGerrissen Aug 17 '10 at 21:09

1 Answers1

1

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555