开发者

How a servlet request data from other servlet?

开发者 https://www.devze.com 2023-02-21 03:10 出处:网络
Ok i was using only response.sendRedirect and forward to work with bought servlets but now i need that a servlet request the answer and not send the client to the other servlet.

Ok i was using only response.sendRedirect and forward to work with bought servlets but now i need that a servlet request the answer and not send the client to the other servlet.

How can i do this ?

let me give a example: Imagine a servlet that gives you the time and the temperature in one page.

int this servlet u ll need to request data from 2 diferent servlets so you will ne开发者_开发问答ed what im asking here...


If the both servlets runs in the same context on the same server, then just use RequestDispatcher#include().

request.getRequestDispatcher("/otherservleturl").include(request, response);

You can even do it in a JSP which is been forwarded by the first servlet.

request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

with

<jsp:include page="/otherservleturl" />

If they don't run in the same context, then you need to programmatically fire a HTTP request on it and pipe its HTTP response output to the current response output.

InputStream input = new URL("http://other.com/servlet").openStream();
OutputStream output = response.getOutputStream();
IOUtils.copy(input, output);

For more advanced HTTP requests, check this mini-tutorial.


Ignore the fact that you're making a request from a servlet - it's just normal Java code.

Ignore the fact that you're making a request to a servlet - it's just a normal HTTP request.

Use whatever you normally use for dealing with HTTP - e.g. Apache HttpClient, or the built-in URLConnection class. Fetch the data, combine it with any other data, serve it as the response.

0

精彩评论

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