How to perform Ajax call from Javascript to JSP?

半城伤御伤魂 提交于 2020-01-06 15:18:42

问题


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.


回答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.



来源:https://stackoverflow.com/questions/3506890/how-to-perform-ajax-call-from-javascript-to-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!