Java.Servlets.What does URL encoding mean? How can it be implemented in Java?

🧠 What is URL Encoding?

✅ URL encoding is the process of translating special characters in a URL into a format that can be safely transmitted over the Internet.

In URLs:

  • Only letters, digits, and a few special characters (-, _, ., ~) are allowed as-is.
  • Spaces, symbols (@, #, ?, =, /, etc.) must be encoded.

🔵 Encoding replaces unsafe characters with a % followed by two hexadecimal digits.

✅ Example:

CharacterEncoded as
Space ()%20
@%40
:%3A
/%2F
?%3F
&%26

🎯 Why do we need URL encoding?

  • To safely pass data inside URLs without confusion.
  • To avoid breaking the URL structure.
  • To transmit non-ASCII characters (like ü, ç, 你好) safely over HTTP.

If you don’t encode properly:

  • URLs can get corrupted.
  • Parameters might be misinterpreted.

⚙️ How to Do URL Encoding in Java

✅ Java provides a built-in class: java.net.URLEncoder

Example:

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class UrlEncodeExample {
    public static void main(String[] args) {
        String original = "Hello World! @2024";
        String encoded = URLEncoder.encode(original, StandardCharsets.UTF_8);
        System.out.println(encoded);
    }
}

✅ Output:

Hello+World%21+%402024

🔵 Note:

  • Spaces become + (in application/x-www-form-urlencoded).
  • Special characters are encoded as %XX.

🛠️ Important:

  • Always specify the character encoding (usually UTF-8).
  • Don’t forget to decode later if needed using URLDecoder.decode()!
import java.net.URLDecoder;

String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
System.out.println(decoded); // back to "Hello World! @2024"

🔥 Example: Sending data safely in a query parameter

Suppose you want to create a link like:

https://example.com/search?query=Hello World! @2024

✅ Correct way:

String query = "Hello World! @2024";
String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);

String url = "https://example.com/search?query=" + encodedQuery;
System.out.println(url);

Result:

https://example.com/search?query=Hello+World%21+%402024

🛡️ Warning:

SituationCorrect Approach
Encoding full URL❌ Don’t encode the whole URL blindly (only parameters!)
Encoding query parameters✅ Always encode values (key/value parts)
Encoding path segments✅ Encode separately if needed

🚀 Quick Summary

ConceptMeaning
URL EncodingConvert unsafe characters in a URL into safe %XX format
Java classURLEncoder.encode(String, Charset)
Common encodingUTF-8
Also decodeUse URLDecoder.decode() when needed
Posted in Без рубрики | Comments Off on Java.Servlets.What does URL encoding mean? How can it be implemented in Java?

Java.Servlet.Explain the SingleThreadModel interface.

🧠 What is SingleThreadModel?

✅ SingleThreadModel is an interface that was introduced in early Servlet API versions (Servlet 2.0) to guarantee that:

Only one thread can execute the servlet’s service() method at a time per servlet instance.

🎯 How It Worked:

If your servlet implemented SingleThreadModel:

public class MyServlet extends HttpServlet implements SingleThreadModel {
    // servlet code
}

✅ The container (e.g., Tomcat) ensured that:

  • Each request is handled one at a time for each servlet instance.
  • OR the container creates a pool of servlet instances to handle multiple requests safely.

✅ Result:

  • No two threads could access the same servlet instance at the same time.
  • It was supposed to make servlets thread-safe easily.

⚡ But there were BIG problems:

ProblemWhy it mattered
Performance impactSlowed down server a lot — couldn’t use threads fully
Didn’t really solve all thread issuesShared resources (like database connections, static fields) could still cause problems
Complexity for server implementersContainers had to create and manage multiple servlet instances
Developers misunderstood itThought “thread safe” meant “no need to think anymore” — which was wrong

🚨 Important: SingleThreadModel is Deprecated!

  • Deprecated since Servlet 2.4 (around 2003).
  • Removed in Servlet 3.1+ (modern servers don’t use it anymore).

✅ Today, best practice is to:

  • Write thread-safe code manually.
  • Avoid shared mutable state inside servlets.
  • Use local variables, thread-safe collections (ConcurrentHashMap, AtomicInteger), or proper synchronization when necessary.

🛠️ Quick Example

❌ Old style:

public class OldServlet extends HttpServlet implements SingleThreadModel {
    private int counter = 0; // No synchronization needed because only one thread!

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        counter++;
        resp.getWriter().println("Counter: " + counter);
    }
}

✅ Modern style (no SingleThreadModel, safe by design):

public class SafeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int counter = 0; // local to the method = no thread issues
        counter++;
        resp.getWriter().println("Counter: " + counter);
    }
}

🔥 Quick Summary

QuestionAnswer
What is SingleThreadModel?An interface to make servlet instances accessed by only one thread at a time.
Why it existed?To make servlets “thread-safe” easily.
Why it’s bad?Killed performance, didn’t solve real-world multi-threading issues.
Status now?Deprecated and not recommended.
Modern advice?Manually design thread-safe servlets without SingleThreadModel.

⚡ Final Memory Trick:

“SingleThreadModel was training wheels… but now developers must ride the bike themselves. 🚲“

✅ Always design servlets as multi-threaded apps today!

Posted in Без рубрики | Comments Off on Java.Servlet.Explain the SingleThreadModel interface.

Java.Servlet.Can PrintWriter and ServletOutputStream be used simultaneously in a servlet?

❌ No, you cannot use both PrintWriter and ServletOutputStream simultaneously in a servlet for the same response.

It is forbidden by the Servlet specification.
Mixing them causes IllegalStateException.


🧠 Why?

  • The response can either be character-based (PrintWriter) or byte-based (ServletOutputStream).
  • Not both.
  • Once you get one, the underlying response output handling is set (to either character encoding mode or binary mode).
  • Mixing would break the HTTP response stream.

⚡ Example of what NOT to do:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
    PrintWriter writer = response.getWriter();
    ServletOutputStream outputStream = response.getOutputStream(); // ❌ WRONG!
}

✅ As soon as you call response.getWriter(), trying to call response.getOutputStream() will throw an exception at runtime.

Or vice versa.

🎯 Servlet Specification (Official) says:

If getWriter() has been called, then calling getOutputStream() must throw an IllegalStateException, and vice versa.

🚀 How to decide which one to use?

SituationUse
You send text (HTML, JSON, plain text)PrintWriter
You send binary data (images, PDFs, zip files)ServletOutputStream

✅ Always pick one early when building the response, depending on what you’re sending.

🛠️ Correct usage examples

✅ Use only PrintWriter:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<h1>Hello World!</h1>");
}

✅ Use only ServletOutputStream:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    ServletOutputStream out = response.getOutputStream();
    out.write(new byte[]{1, 2, 3, 4});
}

🔥 Super Quick Summary:

PrintWriterServletOutputStream
TypeCharacter streamByte stream
getWriter() locks response intoCharacter mode
getOutputStream() locks response intoBinary mode
Use both together?❌ NO, IllegalStateException
Posted in Без рубрики | Comments Off on Java.Servlet.Can PrintWriter and ServletOutputStream be used simultaneously in a servlet?

Java.Servlet.What is the difference between PrintWriter and ServletOutputStream?

Both are used to send data from your servlet back to the client as part of the HTTP response.

But they are a little different:

FeaturePrintWriterServletOutputStream
Data typeCharacter stream (text data)Byte stream (binary data)
Best forWriting textual content (HTML, JSON, plain text)Writing binary content (images, PDFs, videos, file downloads)
Returned byresponse.getWriter()response.getOutputStream()
Encoding controlAutomatically handles encoding (e.g., UTF-8)You manually control bytes
Ease of useEasier for textNeeded for non-text (images, files)

🎯 In simpler words:

  • PrintWriter:
    • Works with characters (strings, text).
    • Buffered, convenient for writing HTML, JSON, plain text.
  • ServletOutputStream:
    • Works with raw bytes (binary).
    • Needed when you send binary data like files, images, etc.

🛠️ Tiny Example:

✅ Using PrintWriter for text:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<h1>Hello, World!</h1>");
}

✅ Using ServletOutputStream for binary data:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    ServletOutputStream out = response.getOutputStream();
    byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in bytes
    out.write(data);
}

⚡ Important Rule:

You can’t use both getWriter() and getOutputStream() in the same response!

  • If you call response.getWriter(), you cannot later call response.getOutputStream().
  • And vice versa.
  • Doing so causes IllegalStateException.

Because:

  • Writer and OutputStream are two different ways to manage the response body, and mixing them would break the HTTP response format.

🔥 Quick Practical Tip:

You want to send…Use…
HTML pagePrintWriter
JSON responsePrintWriter
Text file (plain text)PrintWriter
Image (PNG, JPEG)ServletOutputStream
PDF documentServletOutputStream
Zip file downloadServletOutputStream

🚀 Bonus Tip:

If you use PrintWriter, you should always set the character encoding early, for example:

response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

Otherwise the server default encoding (ISO-8859-1) might be used, causing weird text problems.

🛠️ Quick Summary Table:

AspectPrintWriterServletOutputStream
TypeText / Character streamBinary / Byte stream
Use forHTML, JSON, plain textImages, files, binary blobs
Methodresponse.getWriter()response.getOutputStream()
Can mix them?❌ No❌ No
Posted in Без рубрики | Comments Off on Java.Servlet.What is the difference between PrintWriter and ServletOutputStream?

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 data — should 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

Posted in Без рубрики | Comments Off on Java.Servlet.What is the difference between GET and POST?

Java.Servlet.What are the methods for sending data from the client to the server?

🧠 How Can a Client Send Data to the Server?

There are several ways a client (like a browser or app) can send data to a server:


🎯 1. Using HTTP GET Parameters

  • Data is sent in the URL as query string parameters.
  • Format: ?key1=value1&key2=value2

✅ Example:

https://example.com/search?query=shoes&sort=price
  • Server reads data via request.getParameter("query") and request.getParameter("sort").

⚡ Limitations:

  • URL length is limited (~2KB–8KB depending on browser).
  • Data is visible in the address bar (not secure).

✅ Best for:

  • Simple searches
  • Bookmarkable URLs

🎯 2. Using HTTP POST Body

  • Data is sent inside the body of the HTTP request, not in the URL.
  • Typically used when submitting forms, login credentials, file uploads, API data.

✅ Example (HTML form):

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

✅ Example (JavaScript fetch):

fetch('/submit', {
  method: 'POST',
  body: JSON.stringify({ username: "Alice", password: "secret" }),
  headers: { "Content-Type": "application/json" }
});

⚡ Server reads the body via request.getInputStream() or request.getReader().
Or uses frameworks that parse it automatically.

✅ Best for:

  • Sensitive data (e.g., passwords)
  • Large amount of data
  • Structured data (like JSON)

🎯 3. Using HTTP PUT / PATCH

  • Very similar to POST.
  • Sends data in the body to update an existing resource.

✅ Example:

fetch('/user/123', {
  method: 'PUT',
  body: JSON.stringify({ name: "New Name" }),
  headers: { "Content-Type": "application/json" }
});
  • PUT replaces an entire resource.
  • PATCH modifies part of a resource.

✅ Best for:

  • REST APIs
  • Resource updates

🎯 4. Using HTTP Headers

  • Sometimes small pieces of data are sent via HTTP headers.
  • Example: Tokens, API keys, custom client info.

✅ Example:

fetch('/secure-data', {
  method: 'GET',
  headers: {
    "Authorization": "Bearer abc123token",
    "X-Custom-Header": "some-value"
  }
});

⚡ Not for large data, but great for metadata.

🎯 5. WebSockets

  • If using WebSockets, client and server can continuously exchange data after initial handshake.
  • More advanced than basic HTTP — full-duplex communication.

✅ Example (JavaScript):

const socket = new WebSocket('ws://example.com/socket');
socket.send("Hello Server!");

✅ Best for:

  • Real-time applications (chat apps, live updates, games).

🎯 6. Multipart/Form-Data (File Uploads)

  • Used for sending files or complex forms.

✅ Example:

<form method="POST" action="/upload" enctype="multipart/form-data">
  <input type="file" name="file">
  <button type="submit">Upload</button>
</form>

⚡ Server needs to parse multipart/form-data format.

✅ Best for:

  • File uploads
  • Forms with files and text together

🛠️ Quick Summary Table:

WayTransportUse Case
GET query parametersURLSimple data, search
POST bodyHTTP bodyForms, login, API
PUT/PATCH bodyHTTP bodyResource updates (REST)
HTTP HeadersHTTP headersTokens, client metadata
WebSocketsPersistent connectionReal-time apps
Multipart/Form-DataHTTP bodyFile uploads

⚡ Practical Rule:

If you need…Use…
Small and public dataGET query params
Private or large dataPOST/PUT body
Metadata (auth, tokens)Headers
FilesMultipart POST
Real-time messagingWebSockets

🔥 Bonus Tip:

  • GET is idempotent and safe (should not change server state).
  • POST/PUT/PATCH can change the server state (create/update resources).
Posted in Без рубрики | Comments Off on Java.Servlet.What are the methods for sending data from the client to the server?

Java.Servlets.Which HTTP method is not immutable?

🧠 First: What is an immutable HTTP method?

In HTTP, a method is considered immutable (or safe) if:

  • It does NOT change anything on the server.
  • It’s supposed to be read-only (just retrieves data).

✅ Examples of immutable (safe) methods:

MethodSafe?What it does
GET✅ YesRetrieves a resource (no changes)
HEAD✅ YesSame as GET but no response body
OPTIONS✅ YesAsks what methods are supported
TRACE✅ YesEchoes the request for diagnostics

🎯 Now, answering your question:

Which HTTP method is not immutable?

👉 POST is not immutable!

✅ POST is intended to:

  • Create new resources
  • Modify server-side data
  • Submit forms
  • Trigger side-effects (e.g., send email, update a database)

Thus, POST changes server state —
→ so it’s not immutable (not safe).


🚀 Other HTTP methods that are also not immutable:

MethodMutabilityPurpose
POSTMutableCreate or process a resource
PUTMutableReplace a resource
DELETEMutableRemove a resource
PATCHMutablePartially update a resource

All of these modify the server somehow.


🛠️ Quick Summary:

HTTP MethodImmutable (Safe)?
GET✅ Yes
HEAD✅ Yes
OPTIONS✅ Yes
TRACE✅ Yes
POST❌ No
PUT❌ No
DELETE❌ No
PATCH❌ No

⚡ Very simple memory trick:

If the methodThen
Only reads / asks✅ Immutable (safe)
Creates / updates / deletes❌ Not immutable (unsafe)
Posted in Без рубрики | Comments Off on Java.Servlets.Which HTTP method is not immutable?

Java.Servlet.Should I worry about multithreaded safety when working with servlets?

The short answer is:
👉 Yes, you absolutely should worry about thread safety when working with servlets.

Let’s break this down very clearly:


🧠 Why?

  • In a servlet container (like Tomcat, Jetty, etc.),
    only one instance of your servlet class is created by default.
  • Many threads (one per incoming request) are sent to the same servlet instance to handle requests at the same time.
  • This means multiple threads can execute your doGet(), doPost(), etc. simultaneously!

⚡ If you have shared mutable state in your servlet (like instance variables),
you risk:

  • Race conditions
  • Inconsistent data
  • Deadlocks
  • Security issues

🎯 Very Important:

Servlet ObjectShared between Threads?Thread Safe?
Servlet instance✅ Yes (one instance for all threads)❌ No (you must protect shared data)
HttpServletRequest❌ No (each thread gets its own request)✅ Yes (no need to protect)
HttpServletResponse❌ No (each thread gets its own response)✅ Yes (no need to protect)

✅ Request and Response objects are thread-safe (separate for each request).
❌ Servlet instance fields are shared (dangerous if modified).


🛠️ Bad Example (NOT thread-safe!)

public class UnsafeServlet extends HttpServlet {
    private int counter = 0; // SHARED mutable field!

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        counter++;  // NOT thread-safe!
        resp.getWriter().println("Counter: " + counter);
    }
}

Problem:

  • Two users might increase counter at the same time, causing wrong values (lost updates).

✅ Correct Approaches

1. Avoid using instance variables

Simply use only local variables inside doGet(), doPost():

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    int counter = 0; // local to this request
    counter++;
    resp.getWriter().println("Counter: " + counter);
}

2. Use thread-safe objects (if you must share state)

  • Use AtomicInteger, ConcurrentHashMap, etc.
private AtomicInteger counter = new AtomicInteger(0);

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    int currentCount = counter.incrementAndGet();
    resp.getWriter().println("Counter: " + currentCount);
}

✅ AtomicInteger safely increments across threads without race conditions.

3. Synchronize carefully (but try to avoid it)

You can synchronize manually:

private int counter = 0;

@Override
protected synchronized void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    counter++;
    resp.getWriter().println("Counter: " + counter);
}

⚡ But beware:

  • Synchronization can cause performance bottlenecks under heavy load.
  • Better to design without shared mutable state whenever possible.

🛡️ Practical Rule of Thumb:

QuestionBest Practice
Do you need to store data per request?✅ Use local variables.
Do you need to share data across users?✅ Use thread-safe collections / atomic variables / application scope (carefully).
Do you need locks?❌ Only if absolutely necessary, otherwise redesign.

🔥 Real-Life Examples of Servlet Thread Safety Issues:

  • Incorrect login counters
  • Random failures in shopping carts
  • Inconsistent session management
  • Mixed-up responses between users

Almost always caused by improperly handled shared variables inside servlets.


🛠️ Quick Recap

AspectServlet Behavior
Servlet instance per app?✅ Yes, only one
Multiple threads per servlet?✅ Yes
Safe to use instance fields?❌ No, unless they are thread-safe
Local variables inside doGet()?✅ Yes, perfectly safe
Use Atomic*, Concurrent* types for shared data?✅ Yes, best practice
Posted in Без рубрики | Comments Off on Java.Servlet.Should I worry about multithreaded safety when working with servlets?

Java.Servlet.What are the main methods in the HttpServlet class?

🧠 Main Methods in HttpServlet

Here’s the main methods grouped by their purpose:

PurposeMethodDescription
Core dispatchingservice(HttpServletRequest req, HttpServletResponse resp)Dispatches the HTTP request to doGet(), doPost(), etc., based on HTTP method
Handle GET requestdoGet(HttpServletRequest req, HttpServletResponse resp)Handles HTTP GET requests
Handle POST requestdoPost(HttpServletRequest req, HttpServletResponse resp)Handles HTTP POST requests
Handle PUT requestdoPut(HttpServletRequest req, HttpServletResponse resp)Handles HTTP PUT requests
Handle DELETE requestdoDelete(HttpServletRequest req, HttpServletResponse resp)Handles HTTP DELETE requests
Handle HEAD requestdoHead(HttpServletRequest req, HttpServletResponse resp)Handles HTTP HEAD requests (like GET but without body)
Handle OPTIONS requestdoOptions(HttpServletRequest req, HttpServletResponse resp)Handles HTTP OPTIONS (returns allowed methods)
Handle TRACE requestdoTrace(HttpServletRequest req, HttpServletResponse resp)Handles HTTP TRACE (echoes back the request for debugging)

🎯 Quick Details on Each Important Method


✅ 1. service(HttpServletRequest req, HttpServletResponse resp)

  • Called by the servlet container (Tomcat, Jetty, etc.)
  • Decides which doXxx() method to call depending on HTTP method (GET, POST, PUT, etc.).

✅ 2. doGet(HttpServletRequest req, HttpServletResponse resp)

  • For handling normal browser requests.
  • Example: User clicks a link or types a URL.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.getWriter().println("Hello, GET!");
}

✅ 3. doPost(HttpServletRequest req, HttpServletResponse resp)

  • For handling form submissions, data posting, etc.
  • Example: User submits a login form.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username = req.getParameter("username");
    resp.getWriter().println("Posted username: " + username);
}

✅ 4. doPut(HttpServletRequest req, HttpServletResponse resp)

  • For updating resources (e.g., REST APIs).

✅ 5. doDelete(HttpServletRequest req, HttpServletResponse resp)

  • For deleting resources (e.g., REST APIs).

✅ 6. doHead(HttpServletRequest req, HttpServletResponse resp)

  • Same as doGet(), but without sending response body.
  • Used to check metadata like Content-Length, headers, etc.

✅ 7. doOptions(HttpServletRequest req, HttpServletResponse resp)

  • Returns allowed HTTP methods for a resource.
  • Server automatically sets "Allow: GET, POST, PUT, DELETE, OPTIONS" header.

✅ 8. doTrace(HttpServletRequest req, HttpServletResponse resp)

  • Echoes back the received request.
  • Rarely used (mostly for network diagnostics).

⚡ Quick Visual Map

Browser → Servlet Container → HttpServlet.service()
         ├── if GET     → doGet()
         ├── if POST    → doPost()
         ├── if PUT     → doPut()
         ├── if DELETE  → doDelete()
         ├── if HEAD    → doHead()
         ├── if OPTIONS → doOptions()
         └── if TRACE   → doTrace()

🛠️ Bonus Tip:

You can override only the methods you need.
For example:

  • A login servlet usually overrides only doPost().
  • A catalog page usually overrides only doGet().

🔥 Final Mini Summary

MethodWhen to Override
service()Rare — only for very custom dispatching
doGet()Handle page loads, URL clicks
doPost()Handle form submissions, API posts
doPut()Handle updating resources (REST APIs)
doDelete()Handle deleting resources (REST APIs)
doHead()Handle HEAD requests (metadata only)
doOptions()Handle OPTIONS pre-flight (CORS, allowed methods)
doTrace()Handle TRACE requests (debugging, rare)
Posted in Без рубрики | Comments Off on Java.Servlet.What are the main methods in the HttpServlet class?

Java.Servlet.Why is the HttpServlet class declared as abstract?

✅ Because it is designed to be extended, not used directly.

  • HttpServlet provides basic HTTP-specific functionality:
    • It implements the service() method to automatically dispatch requests based on the HTTP method (GET, POST, PUT, DELETE, etc.).
  • But it does not know what your application logic should do in doGet(), doPost(), etc.

👉 So the framework says:

“Hey developer, I’ll take care of the boring stuff.
You just override the methods you care about!”

Thus, it’s declared abstract to force you to create your own subclass and implement specific behavior.

🎯 What Happens Internally

✅ In HttpServlet:

  • service() is implemented like this (simplified):
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String method = req.getMethod();

    if (method.equals("GET")) {
        doGet(req, resp);
    } else if (method.equals("POST")) {
        doPost(req, resp);
    }
    // etc.
}
  • But doGet(), doPost(), etc. are empty by default!

Example of default doGet() inside HttpServlet:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "GET not supported");
}

➡️ So if you don’t override doGet(), your servlet will respond with 405 Method Not Allowed!

🚀 In short:

ReasonWhy
HttpServlet is abstractBecause it expects you to extend it and provide your own business logic
Default behaviorProvides structure but no meaningful handling for any HTTP method
Prevents misuseYou can’t accidentally create a servlet that does nothing or breaks protocol
Template patternFollows the Template Method design pattern — defines skeleton, subclasses customize specific steps

🛠️ Real-world analogy:

Think of HttpServlet like a blueprint for a house:

  • It defines the layout (doors, windows, rooms).
  • But YOU decide the interior design (colors, furniture, decorations).

⚡ Quick Summary:

ConceptHttpServlet
Abstract?✅ Yes
Why abstract?Forces you to override doGet(), doPost(), etc. to add real behavior
Provides default service()?✅ Yes, dispatches based on HTTP method
Provides default doGet(), doPost()?✅ Yes, but default is error (you must override)
PatternTemplate Method Pattern
Posted in Без рубрики | Comments Off on Java.Servlet.Why is the HttpServlet class declared as abstract?