Servlet interview questions and answers for Java developers

Servlet interview questions check how well you know the layer every Java web framework still runs on: how the container picks a servlet for a URL, what happens to one servlet instance under many threads, how filters wrap a request, and why a forward fails once the response is committed. Expect lifecycle and mapping questions first, then filters, sessions and async processing, then debugging scenarios from real applications. Answers that name the exact API call and the failure it prevents stand out.

By Published 7 min read

Why servlet questions still come up

Few teams write raw servlets for new features, yet Spring MVC routes every request through a DispatcherServlet, Spring Security is a chain of servlet filters, and many enterprise systems still run hand-written servlets on Tomcat, Jetty or a full application server. Java backend interviews use servlet questions to see whether you understand what the framework is doing for you. JSP rendering has its own page, JSP interview questions, and the broader platform (EJB, JMS, CDI) is covered in J2EE interview questions.

  1. Core APILifecycle methods, URL mapping, request and response objects, and the difference between the servlet and the container.
  2. Cross-cutting piecesFilters, listeners, sessions and cookies, and how a framework such as Spring plugs into them.
  3. Concurrency and asyncThread safety of a shared instance, the container's thread pool, and startAsync for long waits.
  4. Production scenariosIllegalStateException on forward, garbled characters, a filter that runs twice, sessions that leak memory.

Servlet fundamentals questions

First-round questions on the API
QuestionWhat it testsWhat a strong answer shows
What is a servlet and what is a servlet container?RolesA servlet is a Java class that answers requests through the Servlet API. The container (Tomcat, Jetty, Undertow or an application server) owns sockets, threads, the lifecycle and the mapping from URL to servlet.
Walk through the lifecycle.LifecycleThe container loads the class and creates an instance, calls init once, calls service for each request, which dispatches to doGet, doPost and the rest, and calls destroy when the app stops or the servlet is removed.
What does load-on-startup change?StartupWithout it, many containers create the servlet on the first request, so that user pays for initialization. A non-negative value creates it at deploy time, lower numbers first.
How does the container decide which servlet handles /shop/cart/42?Mapping rulesAn exact path match wins, then the longest matching path prefix such as /shop/*, then an extension mapping such as *.do, then the default servlet mapped to /.
Context path, servlet path and path info?Request URL partsFor /store/api/orders/7 with the app at /store and a servlet at /api/*, the context path is /store, the servlet path is /api and the path info is /orders/7.
getParameter versus getAttribute?Data flowParameters come from the client in the query string or form body and are strings. Attributes are objects your own code puts on the request, session or context to pass data along.
What happens if a servlet does not override doPost and a POST arrives?DefaultsThe default implementation in HttpServlet sends an error, typically 405 Method Not Allowed for HTTP/1.1 requests. HEAD is served through doGet with the body discarded.
Annotations or web.xml?Configuration@WebServlet, @WebFilter and @WebListener remove most XML. The deployment descriptor is still the place for ordering filters, error pages and settings that differ per environment, and it can override annotations.
What is ServletConfig versus ServletContext?ScopeServletConfig holds one servlet's init parameters. ServletContext is shared by the whole web application: context parameters, application attributes, resources and logging.
Why is there one instance and many threads?ConcurrencyCreating an object per request would be wasteful, so the container reuses one instance and runs each request on its own thread. That makes instance fields shared state.
First-round questions on the API. Scroll sideways on a small screen.

Request and response mechanics

  • What does it mean for a response to be committed? The status line and headers have been sent to the client, usually because the buffer filled or the code flushed it. After that you cannot change the status, add headers, forward or redirect without an IllegalStateException.
  • Forward versus redirect? A forward hands the same request to another resource inside the server, and the browser URL does not change. A redirect sends a 3xx with a Location header, and the browser makes a new request, so request attributes are gone.
  • forward versus include on a RequestDispatcher? Forward transfers control and clears any uncommitted buffered output. Include runs the other resource and appends its output, and the included resource cannot set the status or headers.
  • Why do accented characters arrive garbled from a form? The request body was decoded with the wrong charset. Call setCharacterEncoding("UTF-8") before the first getParameter, usually in a filter, and set the response content type with a charset before calling getWriter.
  • Can you call getInputStream and getReader on the same request? No, the API allows one or the other. Reading the body for logging in a filter also consumes it, so a wrapper that caches the body is needed if the servlet must read it again.
  • sendError versus setStatus? sendError commits the response and lets the container show its configured error page. setStatus only sets the code and leaves the body to you.
  • How do you serve a file download? Set the content type and a Content-Disposition attachment header, stream the file through the output stream in chunks, and never load a large file fully into memory.

Filters, wrappers and listeners

@WebFilter(urlPatterns = "/*", asyncSupported = true)
public class RequestTimingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String id = UUID.randomUUID().toString();
        response.setHeader("X-Request-Id", id);   // before the body is written
        long start = System.nanoTime();
        try {
            chain.doFilter(request, response);       // the servlet runs here
        } finally {
            long ms = (System.nanoTime() - start) / 1_000_000;
            request.getServletContext().log(id + " " + request.getRequestURI() + " " + ms + "ms");
        }
    }
}
A filter that tags each request with an ID and logs the time taken. Not executed: it needs the Jakarta Servlet API and a container.
Intermediate questions on the pieces around a servlet
QuestionWhat it testsWhat a strong answer shows
What happens if a filter does not call chain.doFilter?Chain controlThe request stops there. That is how an authentication filter rejects a call, by writing a 401 or redirecting instead of continuing.
How is the order of filters decided?OrderingIn web.xml, by the order of filter-mapping elements. For filters declared only by annotation the order is not defined by the spec, so teams that need a fixed order use the descriptor or the framework's registration with an explicit order.
What are dispatcher types?Forwards and errorsA filter mapping applies to REQUEST by default. Adding FORWARD, INCLUDE, ERROR or ASYNC makes it also run for internal dispatches. A filter that seems to run twice is often mapped for both REQUEST and FORWARD.
Why wrap a request or response?DecoratorsHttpServletRequestWrapper and HttpServletResponseWrapper let a filter change what the servlet sees: cache the body, add headers, or capture output to compress or rewrite it.
Which listeners have you used?Lifecycle hooksServletContextListener for building and closing shared resources, HttpSessionListener for counting or cleaning up sessions, ServletRequestListener for per-request setup, and attribute listeners for auditing changes.
Where would you open a connection pool in a plain servlet app?Resource setupIn contextInitialized of a ServletContextListener, stored as a context attribute, and closed in contextDestroyed so redeploys do not leak threads or connections. Many servers provide the pool through JNDI instead.
How does Spring hook into a servlet container?Framework glueThrough a ServletContainerInitializer or, in Spring Boot, an embedded container that registers the DispatcherServlet and filters programmatically. Spring Security sits in the filter chain behind a single delegating filter.
Intermediate questions on the pieces around a servlet. Scroll sideways on a small screen.

Sessions, cookies and security

  • How does the container track a session? By a session ID, normally in a cookie named JSESSIONID, with URL rewriting through encodeURL as a fallback when cookies are off. The session data itself stays on the server.
  • getSession() versus getSession(false)? The first creates a session if none exists. The second returns null instead, which is what a filter checking for a logged-in user should use so it does not create empty sessions for every anonymous request.
  • How do you prevent session fixation? Issue a new session ID at login with request.changeSessionId() or by invalidating the old session and creating a new one, so an ID planted before login is worthless afterward.
  • Which cookie attributes matter for the session cookie? HttpOnly to keep scripts from reading it, Secure so it only travels over HTTPS, and SameSite to limit cross-site sending. How SameSite is set depends on the container and spec version, so check yours.
  • What makes session replication in a cluster fail? Attributes that are not Serializable, very large objects in the session, and code that mutates an attribute without calling setAttribute again, so the change never replicates.
  • Session timeout units? In web.xml the session-config timeout is in minutes, while setMaxInactiveInterval takes seconds. Mixing them up is a classic production bug.
  • What is declarative security in the servlet spec? Security constraints on URL patterns and HTTP methods with required roles, plus a login configuration, enforced by the container. In code, isUserInRole and getUserPrincipal read the result.

Async, uploads and senior scenarios

@WebServlet(urlPatterns = "/reports/slow", asyncSupported = true)
public class SlowReportServlet extends HttpServlet {
    private final ExecutorService workers = Executors.newFixedThreadPool(8);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        AsyncContext ctx = req.startAsync();
        ctx.setTimeout(30_000);
        workers.submit(() -> {
            try {
                String body = ReportService.build(req.getParameter("id"));
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(body);
            } catch (Exception e) {
                resp.setStatus(500);
            } finally {
                ctx.complete();
            }
        });
    }

    @Override
    public void destroy() {
        workers.shutdown();
    }
}
An async servlet that frees the container thread while a slow report runs elsewhere. Not executed: it needs the Jakarta Servlet API and a container.
Scenarios for experienced Java developers
Scenario or questionLikely cause or topicWhat a strong answer covers
startAsync throws IllegalStateException.asyncSupportedEvery filter and the servlet in the chain must be marked asyncSupported. One synchronous filter in front is enough to block it.
Under load, all requests hang while the CPU is idle.Thread pool exhaustionRequest threads are blocked on a slow downstream call. Take a thread dump, add timeouts, size the pool to the real bottleneck, and move long waits to async processing.
Forward fails with "Cannot forward after response has been committed".Committed responseSomething wrote or flushed output before the forward, often a large page fragment or an explicit flush. Decide the target before writing, or return right after the forward or redirect.
Two users see each other's cart totals.Shared stateAn instance or static field holds request data. Move it to local variables or request attributes, and look for thread-locals that are never cleared on pooled threads.
Memory grows after every redeploy.Classloader leakThreads, JDBC drivers or caches started by the app hold a reference to its classloader. Stop them in contextDestroyed and deregister drivers.
How do you accept file uploads?MultipartMark the servlet with @MultipartConfig and set size limits, then read parts with getPart. Validate the type from the content, not only the filename, and store files outside the web root.
Why did imports change from javax.servlet to jakarta.servlet?Platform historyWhen Java EE moved to the Eclipse Foundation as Jakarta EE, the API packages were renamed. Containers built for the new namespace need migrated code or a conversion tool, which is the main work when upgrading an old app to a current Tomcat line.
When would you still write a raw servlet today?JudgmentA tiny internal endpoint, a health check in a legacy app, a streaming or proxy case where a framework adds little, or maintaining existing code. For new APIs most teams choose a framework built on top.
Scenarios for experienced Java developers. Scroll sideways on a small screen.

Fictional example

Answering "Our login filter runs twice on some pages"
Interviewer
Logs show the authentication filter running twice for some URLs but once for others. What is happening?
Candidate
I would first check which URLs double up. If they are pages a controller forwards to a view, the filter mapping probably includes the FORWARD dispatcher type as well as REQUEST, so it runs for the original request and again for the internal forward. I would confirm by logging getDispatcherType() in the filter. The fix is to map the filter for REQUEST only, or have it mark the request with an attribute and skip itself if the mark is present. If the URLs are error pages instead, the ERROR dispatcher is the likely cause, and I would decide whether error responses really need an authentication check.

How to prepare in five sessions

  1. Build a bare servlet appOne servlet, one filter and one listener on a local container. Log every lifecycle call and every filter entry and exit for a single request.
  2. Play with mappingsMap servlets to an exact path, a prefix, an extension and the default, then print the context path, servlet path and path info for a set of URLs.
  3. Break the responseFlush output and then forward, read the body twice, skip the request encoding. Note each exception and message.
  4. Sessions and securityImplement login with a new session ID, set cookie attributes, and protect a path with a filter that uses getSession(false).
  5. Go asyncTurn a slow endpoint into an async servlet, then add a synchronous filter in front and read the error it causes.

Servlets connect to several neighboring topics. Spring Security interview questions builds directly on the filter chain described here, Spring Boot interview questions covers the embedded container setup, and data-heavy endpoints lead into SQL joins interview questions.

Servlet answers lean on precise API names, and a quick mock round shows where you blur them. Natively, an AI interview assistant for Mac and Windows, writes a transcript of your practice session on the computer, which makes it easy to spot where you said "some method" instead of naming it. In rehearsal it can read a stack trace or a snippet from a screenshot and suggest which part of the request lifecycle to examine. Pro and the free trial let it draw on the résumé and job description you add, and your notes stay saved for review afterward.

Questions people ask

What servlet questions are asked in Java interviews?

The lifecycle, how URL patterns are matched, forward versus redirect, filters and listeners, session handling, thread safety of a shared servlet instance, and async servlets.

Is a servlet thread-safe?

Not by default. The container usually creates one instance and runs many requests on it at the same time, so instance fields are shared. Keep request data in local variables or request attributes.

What is the difference between a filter and a servlet?

A servlet produces the response for a URL. A filter wraps requests to many URLs and runs before and after the servlet for work such as authentication, logging and encoding.

Are servlets still relevant with Spring Boot?

Yes. Spring MVC runs on a DispatcherServlet inside an embedded servlet container, and Spring Security is built from servlet filters, so the servlet model explains how those frameworks behave.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP