Java.Servlet.What is the difference between GET and POST?

🧠 Main Differences Between GET and POST

FeatureGETPOST
Where data is sentIn the URL as query string (?key=value)In the HTTP request body
VisibilityData is visible in the URLData is hidden (not shown in URL)
Amount of dataLimited (browser/server URL length limits, ~2-8 KB)Unlimited or much larger payloads allowed
CachingCached by browsers and proxies by defaultNot cached by default
Bookmarkable✅ Yes (because URL contains data)❌ No (data is not in URL)
Safe (no side effects)?✅ Yes (should not change server state)❌ No (meant to modify or create resources)
Idempotent✅ Yes (same request = same result, usually)❓ No (repeating can cause different effects, e.g., creating two users)
Use caseRetrieve or query dataSubmit data, create or update on server

🎯 Deeper Explanation:

GET

  • Designed to retrieve datashould not change anything on the server.
  • Can be cached and pre-fetched by browsers.
  • Example:
https://example.com/search?query=shoes

In servlet, you read it like:

String query = request.getParameter("query");

POST

  • Designed to send data to the server to modify, create, or process something.
  • Should NOT be cached.
  • Example:

Sending a form:

<form method="POST" action="/submit">
  <input name="username">
  <input name="password" type="password">
  <button type="submit">Login</button>
</form>

In servlet:

String username = request.getParameter("username");
String password = request.getParameter("password");

🔥 Practical Differences

SituationGETPOST
Searching Google
Logging into an account❌ (not secure)
Deleting a user❌ (should not use GET)
Sending a file
Navigating to a page

🛡️ Important Security Note:

  • Sending passwords, tokens, or sensitive info via GET is very bad because:
    • It can be logged in browser history.
    • It can be cached.
    • It can be saved in server logs.

✅ Always use POST (or better yet, secure APIs) for sensitive data.


⚡ Quick Memory Trick:

ThinkMeaning
“Just getting something”Use GET
“Sending something new or important”Use POST

🛠️ Real Example

GET URL:

https://example.com/profile?userId=123
  • Read profile for user 123.

POST Request:

POST /profile/update
{
  "name": "Alice",
  "email": "alice@example.com"
}
  • Update profile data for user.

🚀 Tiny Bonus:

HTTP spec says:

  • GET should be safe and idempotent (no changes, no side effects).
  • POST is unsafe and not necessarily idempotent (changes happen).

🛠 Quick Summary Table

GETPOST
Retrieve data?
Submit/create data?
Data in URL?
Data in Body?
Caching?✅ Likely❌ No
Visible to user?
Suitable for sensitive data?❌ No✅ Yes

This entry was posted in Без рубрики. Bookmark the permalink.