doGet() vs. doPost()

0
940

In this post we are going to look at the details and difference between doGet() and doPost() methods. We have seen the servlet life cycle already in an earlier post and have looked at the service part of it. So when you invoke a servlet, the servlet engine passes the information to the servlet service() method. This method determines the type of request made (get, post, head, put,…) and calls the function doXxxx(), like doGet(), doPost(), etc. user should override one or both to perform the servlet’s actions and should not override service().

So which one gets called when ?

doGet() is called in response to an Http Get request. This happens when user clicks on a link or enter a URL into the browser’s address bar. It also happens with some HTML forms (with method=”Get”).

AND

doPost() is called in response to an Http Post request. This happens with some HTML forms (method = “post”).

Lets have a closer look at the differences between both:

GET

  1. Retrieves information such as a simple HTML page or the results of a database query.
  2. Supports queryStrings (name-value pairs appended to the URL). Servers limit query string to about 1024 chars.
  3. Allows bookmarks.

POST

  1.  Sends information to the server such as form fields, larger text bodies and key-value pairs.
  2. It hides form data because it is not passed as a query string but in the message body.
  3. It sends unlimited length data as part of its http request body.
  4. Does not allow bookmarks.

So which one to use when ? doGet() or doPost() ?

Conclusion

Always prefer Get, except if :

  • Data is sensitive
  • Data is greater than 1024 chars
  • Application does not need bookmarks

simply because Get is faster than Post 😉

Disclaimer : This is my understanding based on the knowledge I have acquired. If you have different views, feel free to share.

Previous articleMongoDB-Java Integration
Next articleJava Serialization
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY