Java.Servlet.What are the differences between GenericServlet and HttpServlet?

🧠 First: What are GenericServlet and HttpServlet?

ClassMeaning
GenericServletAn abstract class designed for any type of protocol (not just HTTP).
HttpServletA concrete class specifically for HTTP protocol (GET, POST, PUT, DELETE, etc.).

Both help you avoid writing Servlet API code from scratch — they implement some boring methods for you already.

🎯 Key Differences Between GenericServlet and HttpServlet

FeatureGenericServletHttpServlet
Designed forGeneric protocols (could be HTTP, FTP, SMTP, etc.)HTTP protocol only
Direct subclass ofServlet interfaceGenericServlet
Supports HTTP methods like GET, POST?❌ No (you implement service() manually)✅ Yes (provides doGet(), doPost(), etc.)
Default service() method?You must override service(ServletRequest, ServletResponse) yourselfAlready implemented; dispatches automatically to doGet(), doPost(), etc.
Typical usageVery rare (custom protocols, non-HTTP servers)Very common (web applications)
SimplifiesBasic Servlet lifecycleFull HTTP request/response handling

⚙️ How You Use Them (Code Examples)

✅ Using GenericServlet
(You must override service() and manually check protocol yourself if needed)

public class MyGenericServlet extends GenericServlet {
    @Override
    public void service(ServletRequest request, ServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("Hello from GenericServlet");
    }
}
  • No help with HTTP headers, status codes, etc.
  • Very low-level.

✅ Using HttpServlet
(You override doGet(), doPost(), etc., and server handles routing)

public class MyHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("Hello from HttpServlet via GET!");
    }
}
  • Much easier.
  • Server automatically calls doGet() if browser sends GET, doPost() for POST, etc.

🔥 Quick Memory Trick

If you thinkThen
“I want to work with HTTP requests, methods, sessions, cookies.”Use HttpServlet
“I’m building something not tied to HTTP (rare!)”Use GenericServlet

⚡ Quick Recap in 5 Sec:

  • GenericServlet: generic, you handle everything yourself.
  • HttpServlet: HTTP-focused, gives you ready-to-use doGet(), doPost(), doPut(), doDelete(), etc.

In real life → almost always use HttpServlet unless you are building a custom protocol server (which is super rare).

Posted in Без рубрики | Comments Off on Java.Servlet.What are the differences between GenericServlet and HttpServlet?

Java.Servlet.Examples of listeners

🧠 Full List of Important Servlet Listeners + Examples

Listener InterfacePurposeExample Event It Catches
ServletContextListenerApp startup and shutdownServer starts your app, or app is undeployed
HttpSessionListenerSession creation and destructionUser opens a session (new visit) or session expires
ServletRequestListenerRequest creation and destructionEach new HTTP request starts or ends
ServletContextAttributeListenerAttribute added/removed/replaced in contextSomeone puts something into ServletContext
HttpSessionAttributeListenerAttribute added/removed/replaced in sessionUser sets attribute into session
ServletRequestAttributeListenerAttribute added/removed/replaced in requestDeveloper adds data into request object

🎯 Examples for Each Listener


1. ServletContextListener

✅ Do something when the application starts or shuts down.

@WebListener
public class AppStartupShutdownListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("App started at: " + new java.util.Date());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("App is shutting down...");
    }
}

Use case:

  • Initialize DB connections at app start.
  • Clean up threads, close connections at app shutdown.

2. HttpSessionListener

✅ Track when user sessions are created or destroyed.

@WebListener
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("New session created: " + se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("Session destroyed: " + se.getSession().getId());
    }
}

Use case:

  • Count online users.
  • Cleanup session-related resources.

3. ServletRequestListener

✅ Hook into each HTTP request lifecycle.

@WebListener
public class RequestListenerExample implements ServletRequestListener {
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("New request started at " + new java.util.Date());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("Request finished.");
    }
}

Use case:

  • Start timing requests (for performance monitoring).
  • Set up default values for every request.

4. ServletContextAttributeListener

✅ Listen for attributes being added/removed/changed in the application scope.

@WebListener
public class AppAttributeListener implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("Attribute added: " + event.getName() + " = " + event.getValue());
    }
}

Use case:

  • Track global setting changes.
  • Audit what data is being put into ServletContext.

5. HttpSessionAttributeListener

✅ Listen for attributes being added/removed/changed inside a user session.

@WebListener
public class SessionAttributeLogger implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("Session attribute added: " + event.getName());
    }
}

Use case:

  • Track login/logout events stored in session.
  • Auto-update session statistics.

6. ServletRequestAttributeListener

✅ Watch attributes being added/removed/changed in individual requests.

@WebListener
public class RequestAttributeLogger implements ServletRequestAttributeListener {
    @Override
    public void attributeAdded(ServletRequestAttributeEvent event) {
        System.out.println("Request attribute added: " + event.getName() + " = " + event.getValue());
    }
}

Use case:

  • Debugging request data.
  • Auditing sensitive request changes.

🛠️ Quick Memory Table

EventListener
App starts or stopsServletContextListener
User session starts or endsHttpSessionListener
HTTP request begins or endsServletRequestListener
Attribute added/removed at app levelServletContextAttributeListener
Attribute added/removed at session levelHttpSessionAttributeListener
Attribute added/removed at request levelServletRequestAttributeListener

🚨 Bonus Tip:

  • Listeners do not block or control the flow (unlike filters).
  • They are passive observers — they listen and react.
Posted in Без рубрики | Comments Off on Java.Servlet.Examples of listeners

Java.Servlet.Difference between Filters and Listeners

🧠 Main Differences Between Filter and Listener

FeatureFilterListener
What it isInterceptor of requests and responsesEvent handler for lifecycle events
When it runsEvery time a matching request comes inWhen a specific event happens (like app start, session create, request initialize)
Main purposePre-processing and post-processing of requests/responsesObserving and reacting to events
Example useAuthentication, logging, compression, modifying requests or responsesResource cleanup, monitoring session creation, app startup tasks
Works withServletRequest, ServletResponse, FilterChainServletContext, HttpSession, ServletRequest events
Configured by@WebFilter annotation or web.xml@WebListener annotation or web.xml
Flow control?Yes (you can stop the request or modify it!)No (just reacts, can’t control flow)

🎯 In simple words:

  • Filter = Interfere with request/response processing.
  • Listener = React to lifecycle events (e.g., “Hey, someone created a session!”)

🔥 Tiny Examples:

✅ Filter example — Block requests if user is not logged in:

@WebFilter("/secure/*")
public class AuthFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(false);

        if (session == null || session.getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect("/login.jsp");
        } else {
            chain.doFilter(request, response); // continue
        }
    }
}

✅ Listener example — Log when a new session is created:

@WebListener
public class SessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("New session created: " + se.getSession().getId());
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("Session destroyed: " + se.getSession().getId());
    }
}

🛠️ Quick Memory Trick:

TermThink
FilterLike a security gate ➔ can allow, modify, or block
ListenerLike a security camera ➔ just observes and logs

⚡ Bonus: Types of Listeners

There are many listeners depending on what event you want to catch:

  • ServletContextListener ➔ app startup/shutdown
  • HttpSessionListener ➔ session creation/destruction
  • ServletRequestListener ➔ request creation/destruction
  • Plus attribute listeners: ServletContextAttributeListener, HttpSessionAttributeListener, etc.
Posted in Без рубрики | Comments Off on Java.Servlet.Difference between Filters and Listeners

Java.Servlet.What servlet wrapper classes do you know?

🧠 What Are Servlet Wrapper Classes?

Wrapper classes are special decorators that wrap around the original HttpServletRequest, HttpServletResponse, or ServletInputStream/ServletOutputStream.

They allow you to:

  • Intercept or modify behavior
  • Read, change, or log request/response data
  • Implement security, compression, caching, etc.

In short: wrapper = original object + extra behavior (without modifying the original object itself).

🎯 Main Servlet Wrapper Classes (from Java EE / Jakarta EE)

Wrapper ClassWrapsPurpose
HttpServletRequestWrapperHttpServletRequestModify or read the incoming request
HttpServletResponseWrapperHttpServletResponseModify or decorate the outgoing response
ServletRequestWrapperServletRequest (more generic)Modify a basic servlet request
ServletResponseWrapperServletResponse (more generic)Modify a basic servlet response
ServletInputStream (custom wrapper)Servlet input streamIf you want to intercept raw request body
ServletOutputStream (custom wrapper)Servlet output streamIf you want to capture or compress response

🔥 Let’s See Quick Examples:

1. HttpServletRequestWrapper

Used when you want to override some methods from HttpServletRequest.

✅ Example:
Suppose you want to add a fake header to all requests.

public class MyRequestWrapper extends HttpServletRequestWrapper {
    public MyRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        if ("X-Fake-Header".equals(name)) {
            return "FakeHeaderValue";
        }
        return super.getHeader(name);
    }
}

Then inside a Filter:

MyRequestWrapper wrappedRequest = new MyRequestWrapper((HttpServletRequest) request);
chain.doFilter(wrappedRequest, response);

2. HttpServletResponseWrapper

Used when you want to capture or modify the outgoing response.

✅ Example:
Suppose you want to capture response content.

public class MyResponseWrapper extends HttpServletResponseWrapper {
    private StringWriter capture;

    public MyResponseWrapper(HttpServletResponse response) {
        super(response);
        capture = new StringWriter();
    }

    @Override
    public PrintWriter getWriter() {
        return new PrintWriter(capture);
    }

    public String getCapturedData() {
        return capture.toString();
    }
}

You can then analyze the response later in your filter.

3. ServletInputStream / ServletOutputStream Wrappers

These are lower-level and you use them if you want to:

  • Read raw POST body multiple times (normally it can only be read once).
  • Compress output (like GZIP).
  • Encrypt/decrypt stream data.

You would usually extend ServletInputStream or ServletOutputStream and override methods like read(), write(), etc.

🚀 Why Are Wrappers Useful?

  • Security: e.g., sanitize inputs (XSS protection).
  • Logging: log request and response bodies.
  • Compression: wrap response with GZIPOutputStream.
  • Modification: inject or change data on the fly.
  • Caching: cache results of slow operations.

You often use wrappers inside a Filter, because filters are perfect for request/response interception.


⚡ Quick Summary:

You NeedUse This Wrapper
Modify incoming requestHttpServletRequestWrapper
Modify outgoing responseHttpServletResponseWrapper
Modify raw input streamCustom ServletInputStream subclass
Modify raw output streamCustom ServletOutputStream subclass
Modify generic (non-HTTP) requests/responsesServletRequestWrapper / ServletResponseWrapper
Posted in Без рубрики | Comments Off on Java.Servlet.What servlet wrapper classes do you know?

Java.Servlet.How can I get the client’s IP address on the server?

🧠 How to Get the Client’s IP Address in a Servlet

✅ The basic way:

String ipAddress = request.getRemoteAddr();

request.getRemoteAddr() returns the IP address of the client making the request.

Example:

  • If you’re testing locally ➔ might be 127.0.0.1.
  • If a real client ➔ might be 192.168.x.x or even a public IP.
Continue reading →
Posted in Без рубрики | Comments Off on Java.Servlet.How can I get the client’s IP address on the server?

Java.Servlet.How can I get server information from a servlet?

You can easily get server information from inside a servlet using the ServletContext and HttpServletRequest objects.

Let’s go step-by-step:


🛠️ Ways to Get Server Info in a Servlet

1. Get Server Info using ServletContext

ServletContext context = getServletContext();
String serverInfo = context.getServerInfo();

✅ serverInfo will return something like:

Apache Tomcat/9.0.75

or

GlassFish Server Open Source Edition 5.1

GlassFish Server Open Source Edition 5.1

2. Get Server Name, Port, Protocol using HttpServletRequest

Inside your doGet() or doPost() method:

String serverName = request.getServerName();     // e.g., "localhost" or "www.example.com"
int serverPort = request.getServerPort();         // e.g., 8080
String scheme = request.getScheme();              // "http" or "https"
String protocol = request.getProtocol();          // "HTTP/1.1"

✅ Example outputs:

MethodExample Output
getServerName()localhost
getServerPort()8080
getScheme()http
getProtocol()HTTP/1.1

3. Get Servlet Version Info

You can also check the servlet API version your server supports:

int major = context.getMajorVersion();
int minor = context.getMinorVersion();

int major = context.getMajorVersion();
int minor = context.getMinorVersion();

🎯 Full Code Example:





public class ServerInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = getServletContext();

        String serverInfo = context.getServerInfo();
        int majorVersion = context.getMajorVersion();
        int minorVersion = context.getMinorVersion();

        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String scheme = request.getScheme();
        String protocol = request.getProtocol();

        response.setContentType("text/plain");
        response.getWriter().println("Server Info: " + serverInfo);
        response.getWriter().println("Servlet API Version: " + majorVersion + "." + minorVersion);
        response.getWriter().println("Server Name: " + serverName);
        response.getWriter().println("Server Port: " + serverPort);
        response.getWriter().println("Scheme: " + scheme);
        response.getWriter().println("Protocol: " + protocol);
    }
}

⚡ Quick Summary:

⚡ Quick Summary:

You WantHowMethod
Server type and versionServletContext.getServerInfo()
Server hostnameHttpServletRequest.getServerName()
Server portHttpServletRequest.getServerPort()
HTTP scheme (http/https)HttpServletRequest.getScheme()
HTTP protocol versionHttpServletRequest.getProtocol()
Servlet API versionServletContext.getMajorVersion() + getMinorVersion()
Posted in Без рубрики | Comments Off on Java.Servlet.How can I get server information from a servlet?

Java.Servlet.How can I get the actual location of a servlet on the server?

🧠 If you want to get the real file system path (actual location) of a servlet or a resource on the server, you don’t get it directly from the servlet class itself.

Instead, you use the ServletContext object, which represents the web application running on the server.

✅ You can use:

ServletContext context = getServletContext();
String realPath = context.getRealPath("/");

"/" means the root of your web application.

It will give you something like:

/opt/tomcat/webapps/YourApp/

or on Windows:

C:\Program Files\Tomcat 9.0\webapps\YourApp\

🎯 If you want a specific folder or file inside your app:

Example:

String realPath = context.getRealPath("/WEB-INF/config.properties");

This gives you the absolute server path to config.properties inside WEB-INF.

🚀 Full Example inside a Servlet:

public class LocationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = getServletContext();

        String rootPath = context.getRealPath("/");
        String configPath = context.getRealPath("/WEB-INF/config.properties");

        response.setContentType("text/plain");
        response.getWriter().println("Web app root path: " + rootPath);
        response.getWriter().println("Config file path: " + configPath);
    }
}

When you open the servlet, you’ll see actual file paths printed!

⚡ Some Important Notes:

  • If you run your servlet in a packed WAR file (without unpacking), some servers (like Tomcat if configured not to unpack WARs) may return null from getRealPath().
  • getRealPath() only works reliably if the app is exploded (unpacked into folders).
  • Servlet specification says getRealPath() can return null if it can’t resolve the path.

If getRealPath() is null, and you need to load a file, you’d better use:

InputStream is = context.getResourceAsStream("/WEB-INF/config.properties");

instead of relying on file system paths.

🛠️ Quick Summary:

You WantYou UseExample
Root of web appgetRealPath("/")/opt/tomcat/webapps/YourApp/
Specific filegetRealPath("/WEB-INF/file.txt")/opt/tomcat/webapps/YourApp/WEB-INF/file.txt
Stream resource (safe for packed WARs)getResourceAsStream("/WEB-INF/file.txt")Returns InputStream
Posted in Без рубрики | Comments Off on Java.Servlet.How can I get the actual location of a servlet on the server?

Java.Servlet.How can I allow a deadlock in a servlet?

🧠 First, can a servlet have a deadlock?

Yes.
Because servlets are multithreaded:

  • One servlet instance is usually shared between many threads (one thread per request).
  • If you mess with shared resources (like instance variables or external locks) incorrectly, you can cause deadlocks — just like in normal multithreaded Java programs.

🔥 How You Might Allow a Deadlock in a Servlet

Deadlocks usually happen when:

  1. Two (or more) threads hold different locks.
  2. Each thread tries to acquire the other’s lock.
  3. Circular waiting happens — they are stuck forever.

In a servlet, this can happen if:

  • You have two or more synchronized blocks or locks.
  • Threads acquire them in different orders.

⚙️ Here’s an Example to create a Deadlock inside a Servlet:

public class DeadlockServlet extends HttpServlet {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String threadName = Thread.currentThread().getName();
        
        if ("thread1".equals(request.getParameter("thread"))) {
            synchronized (lock1) {
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (lock2) {
                    response.getWriter().println("Thread 1 acquired lock1 and lock2");
                }
            }
        } else if ("thread2".equals(request.getParameter("thread"))) {
            synchronized (lock2) {
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (lock1) {
                    response.getWriter().println("Thread 2 acquired lock2 and lock1");
                }
            }
        } else {
            response.getWriter().println("Specify thread=thread1 or thread2 in URL");
        }
    }
}

What happens here:

  • thread1 locks lock1 first, then tries to lock lock2.
  • thread2 locks lock2 first, then tries to lock lock1.
  • If timing is right (both lock their first lock before trying to get the second),
    💥 deadlock — both threads will wait on each other forever.

🎯 How to trigger the deadlock:

Open two tabs very quickly:

http://localhost:8080/yourapp/deadlockservlet?thread=thread1
http://localhost:8080/yourapp/deadlockservlet?thread=thread2

Both tabs will hang!

⚡ Quick Recap:

Deadlock can happenBecause servlets are multithreaded.
You allow itBy mismanaging multiple locks with inconsistent lock order.
Typical mistakeSynchronized blocks with multiple resources but no consistent locking strategy.

⚠️ Important:

In real-world servlet applications, you should never allow deadlocks.
You’d avoid it by:

  • Always locking resources in a consistent order.
  • Minimizing synchronized blocks.
  • Using higher-level concurrency tools (ReentrantLock, etc.) carefully.
  • Or better, designing to avoid shared mutable state between threads.
Posted in Без рубрики | Comments Off on Java.Servlet.How can I allow a deadlock in a servlet?

Java.Servlet.What are servlet attributes used for and how do I work with them?

Attributes are key-value pairs you can attach to an object like:

  • ServletRequest
  • HttpSession
  • ServletContext

They are used to share data between:

  • Different parts of your servlet (methods, filters)
  • Different servlets
  • Requests across time (session)
Continue reading →
Posted in Без рубрики | Comments Off on Java.Servlet.What are servlet attributes used for and how do I work with them?

Java.Servlet.What is the difference between sendRedirect() and forward()?

Featureforward() (RequestDispatcher)sendRedirect() (HttpServletResponse)
Who handles itServerBrowser (client)
How it worksServer internally forwards the same request to another resource (another servlet, JSP, HTML, etc.)Server tells browser: “Hey, go make a new request to a different URL!”
Browser URL changes?No (URL stays the same)Yes (URL changes to the new target)
New request?No (same request and response objects continue)Yes (new request from browser)
Can pass request attributes?Yes, because it’s the same requestNo, because a new request is made (attributes are lost unless passed as URL params)
Use case exampleForwarding to an error page, controller dispatching internallyRedirecting after a POST to avoid resubmission (Post-Redirect-Get pattern)
PerformanceFaster (no network roundtrip)Slower (extra network call)

In short:

  • forward()
    • Happens inside the server.
    • Invisible to the browser.
    • Request is preserved (attributes stay).
    • More efficient because no second HTTP request.
  • sendRedirect()
    • Browser is told to go to a new URL.
    • New HTTP request.
    • Slower, but useful if you want the user to know they are on a different page.
    • Useful if you want fresh start without carrying old request attributes.

Code Example:

✅ Forward:

RequestDispatcher dispatcher = request.getRequestDispatcher("/dashboard");
dispatcher.forward(request, response);

URL stays the same.

Dashboard is generated using the original request.

✅ Redirect:

response.sendRedirect(request.getContextPath() + "/dashboard");

Browser URL changes to /dashboard.

New request is made by the browser.

A small real-life scenario:

  • Forward:
    • User submits login form.
    • Server forwards internally to a dashboard page because the user is authenticated.
  • Redirect:
    • After user logs out, you redirect them to login page.
    • This way if they press Refresh after logout, it won’t re-execute old logout code again.
Posted in Без рубрики | Comments Off on Java.Servlet.What is the difference between sendRedirect() and forward()?