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”).
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:
- Retrieves information such as a simple HTML page or the results of a database query.
- Supports queryStrings (name-value pairs appended to the URL). Servers limit query string to about 1024 chars.
- Allows bookmarks.
- Sends information to the server such as form fields, larger text bodies and key-value pairs.
- It hides form data because it is not passed as a query string but in the message body.
- It sends unlimited length data as part of its http request body.
- Does not allow bookmarks.
So which one to use when ? doGet() or doPost() ?
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.