The developer should specify to the Browser in what style the data is to be sent to the server. The most commonly used styles and available are GET and POST. These styles are to be written in METHOD attribute of <FORM> tag as follows. Let us see their differences and when to use them in GET vs POST.
<form method="GET" action="http://localhost:8888/india/roses">
In GET style, the data is appended to the URL (written in action attribute in the above statement) and sent to the server and in POST style, the client data is sent separately as message body.
Remember the Login Screen Validation Servlet. The screens are displayed here in relevance to GET style.
Observe the client HTML program when the fields (text boxes) t1 (for user name) and t2 (for password) are filled up.
Observe the URL in browser prompt.
Output screen when submit button is clicked.
Now again, observe the URL in browser prompt. It is as follows.
What we understand by the above URL?
The data of user name (S N Rao) and the password (java) are appended to the URL with a delimiter (separator) of ?, that is, the actual URL separated from the client data with a question mark, ?. Still observe, the spaces in between S N Rao are indicated with + symbol and delimiter & is used to separate two fields of t1 and t2.
Table showing the differences GET vs POST
|Sending of data||Client data is appended to URL and sent||Client data is sent separately|
|Storing in Browser History||As data is appended, the client data is stored in browser history||As data is sent seaprately, the client data is not stored in browser history|
|Bookmark||The URL with client data can be bookmarked. Thereby, later without filling the HTML form, the same data can be sent to server||Not possible to bookmark|
|Encoding or enctype||application/x-www-form-urlencoded||application/x-www-form-urlencoded or multipart/form-data. For binary data, multipart enctype to be used|
|Limitation of data sent||Limited to 2048 characters (browser dependent)||Unlimited data|
|Hacking easiness||Easy to hack the data as data is stored in browser history||Difficult to hack|
|Type of data sent||Only ASCII data can be sent||Any type of data can be sent including binary data|
|Data secrecy||Data is not secret as other people can see the data in browser history||Data is secret as not stored in history|
|When to be used||Prefer when data sent is not secret. Do not use for passwords etc.||Prefer for critical and sensitive data like passwords etc.|
|Cache||Can be caught||Cannot be caught|
|Default||If not mentioned, GET is assumed as default||Should be mentioned explicitly|
|Performance||Relatively faster as data is appeneded to URL||A separate message body is to be created|
Which is to be preferred – GET or POST?
It depends on your application need. If client data includes only ASCII characters, no secrecy and limited to 2KB length (depends on the browser), then prefer GET, else POST.