File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Forwarding from doPost to doGet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Forwarding from doPost to doGet" Watch "Forwarding from doPost to doGet" New topic

Forwarding from doPost to doGet

Jason Kwok
Ranch Hand

Joined: Mar 31, 2005
Posts: 126

I have a login servlet that, as the name would suggest, handles the login functionality of my webapp. If the login is approved, I'm currently forwarding to a static JSP page, but I would rather forward to another servlet that generates a list and let the user proceed from there.

The servlet to generate the list already works, as does the login servlet, it's just a matter of forwarding from one to the other.

The login servlet only has a doPost method, the doGet just returns the request and response objects. In the other servlet, we'll call MyServlet, it uses both doPost and doGet and the listing functionality exists within the doGet method.

Everytime I try to use the RequestDispatcher to forward to the servlet using my servlet mapping, I get an error. Is it possible to go from doPost to doGet? Or would I have to duplicate the list code inside the doPost method?
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

No, the request type (GET, POST, etc...) is determined before your first servlet is ever called and is part of that request for the entire cycle.

A simple way to work with this is to combine your doPost and doGet methods (just have one call the other) so it won't matter which is called.

A more complex way of doing this is to wrap the request object by extending HttpRequestWrapper and overriding getMethod.

If you add a setMethod or changeMethod method, you could change the requests method, and pass the wrapper to the next servlet as an argument to RequestDispatcher's forward method.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Jason Kwok
Ranch Hand

Joined: Mar 31, 2005
Posts: 126
Hi Ben,

Thanks for the advice, I'll check your suggestion out. I've never done something like that before and it sounds rather interesting.

I agree. Here's the link:
subject: Forwarding from doPost to doGet
It's not a secret anymore!