Reputation: 1926
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...
Upvotes: 0
Views: 2658
Reputation: 1109532
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.
Upvotes: 3
Reputation: 1503290
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.
Upvotes: 1