mikizas
mikizas

Reputation: 341

Send parameter from servlet to servlet

I have a servlet load_plan, which its doPost method loads a plan with this code:

int id = Integer.parseInt(request.getParameter("id"));

I have another servlet hire_new_plan, which its doGet method sends the id to the load_plan servlet.

hire_new_plan doPost() --> load_plan doGet().

How can I send the id from the doGet method so that I can capture it with the request.getParameter() in the doPost method of the receiver servlet?

There are two problems as I have read.

First of all, I can't call the doPost method from another servlet's doGet method.

Secondly, it seems as if the request.setAttribute("id", id) doesn't match with the int id = Integer.parseInt(request.getParameter("id"));. I execute in the receiver servlet.

What can I do to fix this?

Upvotes: 0

Views: 2569

Answers (1)

RockAndRoll
RockAndRoll

Reputation: 2287

You can use RequestDispatcher to forward to other servlet.

RequestDispatcher rd = request.getRequestDispatcher("load_plan");
rd.forward(request, response);
//or rd.include(request, response);

While forwarding same request object is sent to the called servlet.So you do not need to do anything.It will be available in that request object by default.

If you go this way,doGet will get called of another servlet. If you can't move your logic in that,I would suggest you to use HttpURLConnection object.You can fire POST request programmatically like this

HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/WebAppName/SecondServlet").openConnection();
connection.setRequestMethod("POST");
InputStream response = connection.getInputStream();
// ... Write to OutputStream of your HttpServletResponse

See More

Upvotes: 1

Related Questions