Skip to content Skip to sidebar Skip to footer

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 se

Solution 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.

protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    URLConnectionconnection=newURL("http://other.service.com").openConnection();
    // Set necessary connection headers, parameters, etc here.InputStreaminput= connection.getInputStream();
    OutputStreamoutput= response.getOutputStream();
    // Set necessary response headers (content type, character encoding, etc) here.byte[] buffer = newbyte[10240];
    for (intlength=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.

Post a Comment for "How To Perform Ajax Call From Javascript To Jsp?"