The difference between GET and POST

There are two principal methods by which a browser interacts with a web server. The most common is the GET method, in which the browser simply requests the contents of a particular URL. When the browser uses this method, the web server ends up calling the servlet's doGet() method.

The second is the POST method, in which the browser "sends" data to a particular URL. For example, it may send some data than a user has entered in a form on a web page. In this case, the servlet's doPost() method is called.

In practice, there is some overlap between the two methods, and your servlet may not even need to care which method is used.

This is because either GET or POST can actually be used to send data from a web form. With the GET method, the data is appended to the URL with a special syntax. You've probably seen URLs such as http://bloggs.com/forum?id=774. Here, the id parameter is given the value 774 directly in the URL. This method is suitable for short data and/or cases where it is desirable for the parameters to be 'visible' in the URL (for example, some search engines pick them up). In the POST method, the URL visible to the user is just http://bloggs.com/forum, and any parameter setting is "hidden" in the communication with the server. (Note that this does not mean encrypted!) For more information about how POST works, see the HTTP specification.

To a servlet, there's really little difference between the two methods. In one case, doGet() will be called, and in the other doPost. But in either case, the servlet container such as Tomcat will already have extracted the HTTP request parameters (be they in the URL or in posted data) and makes them available via the HttpServletRequest object. Unless you specifically care which method is used and want to carry out very different actions accordingly, you can generally make the doPost() method simply pass the request directly to your doGet() method.

Back to servlet introduction and skeleton servlet class.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.