Posting a Request to a Servlet from a Servlet.. (sendRedirect)


Web tier: servlets, JSP, Web frameworks: Posting a Request to a Servlet from a Servlet.. (sendRedirect)

  1. Is it possible to post a request to a different servlet/page from a Servlet. I am using sendRedirect method to redirect to the nxt page but since my URL is too big it get's cut off due to the limitation of the GET Method. Please help me through this.

    Thank You.
  2. YOu can use the getServletNames() method.
    It is a Servlet to Servlet Communication.
    Try this mail me if you get the answer
  3. Hi Pradeep,

    I really appreciate the help. But, from the help what I understood is that the 'getServletNames' would return the list of the names of the Servlet and the my problem is call another Servlet from a Servlet. Say for e.g. I'm in Servlet A and based on certain conditions I would like to direct the user to a different page (which could be a Servlet or a simple HTML page). I can use sendRedirect method of the Response Class but this uses the GET Method to call the page and I want to POST a page..Please let me know if you know the solution to this.

    Any help is appreciated..

    Thank You.

  4. Swati, I don't know for certain whether this will solve your problem, but you can give it a try. In your servlet:

    public void doGet(...)
    String URL = "/servlet/whatever";
    RequestDispatcher rd;
    rd = getServletContext().getRequestDispatcher(URL);

    The HttpRequest object also has a getRequestDispatcher(URI) method. When you use the request dispatcher from the ServletContext, you pass an absolute URI, as in my example. When you get it from the request object you pass a relative URI.

    Also, you may need to change the HTML that invokes your first servlet to use POST rather than GET. The data truncation occurs at the browser and there's no way I'm familiar with to get back what the browsers truncates.


  5. I have understood your problem.
    The technology that supports this requirement is called servlet chainin. But it is a depercated API and it won't last in the coming version of sevlets specifiations.
    I had also encountered the same problem and i effectively resolved it using client side scripting basically Javascript. It's a tricky solution
    The way it can be done is as follows :

    get all the paramters in servlet A.
    e.g you got two paramters paramA, paramB
    Then using outputstream
    (basically out.println("")), write this code from your servlet

    <form name="frmParam" action="/servlet/servletB" method="post">
    <input type="hidden" name="paramA" value="[value of paramA]">
    <input type="hidden" name="paramB" value="[value of paramB]">
    <script language="Javascript">

    It will redirect your page to another page with post method and with you paramneters, like a form (basically it's a form which you submit through Javascript)