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.
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.
Post a Comment for "How To Perform Ajax Call From Javascript To Jsp?"