0

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 need what im asking here...

Winter
  • 1,896
  • 4
  • 32
  • 41

2 Answers2

3

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.

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

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194