Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 119 ยท Practice and Review

Servlet and JSP Interview Questions

Servlet and JSP interview questions with clear answers: HttpServlet, RequestDispatcher, sessions, cookies, URL rewriting, filters, listeners, JSP lifecycle, scopes and more.

Servlets and JSP are older than most of the frameworks built on top of them, yet interviews still ask about them, because they explain what every Java web framework does underneath. A question such as "what is the difference between forward and sendRedirect?" tests whether you understand what really travels between the browser and the server. This lesson collects the questions that come up most often, grouped into servlets, sessions and state, filters and listeners, and JSP, with answers short enough to say out loud.

Try to answer each question before you open it. The Servlet API needs a container such as Tomcat, which cannot run on this page, so code in the answers is read-only; two runnable programs near the end model session handling and JSP scopes. The full lessons are linked from the answers: Servlets, Servlet Requests and Forms, Sessions and Cookies, Filters and Listeners and JSP.

Servlet questions

What is a servlet, and what is the servlet container's job?

A servlet is a Java class that handles HTTP requests and produces responses. It does not have a main method: a servlet container (Tomcat, Jetty, Undertow) listens on the port, parses the HTTP request into an HttpServletRequest, creates a response object, finds the servlet whose URL pattern matches, calls it, and sends the result back. The container also manages the servlet's lifecycle, threads, sessions and security. See Servlets.

What is the difference between GenericServlet and HttpServlet?

GenericServlet is protocol-independent: it implements Servlet and ServletConfig and leaves you to implement service(ServletRequest, ServletResponse). HttpServlet extends it for HTTP: its service method inspects the request method and calls doGet, doPost, doPut, doDelete, doHead or doOptions, and gives you HTTP-specific request and response types. In practice you always extend HttpServlet. (The package is jakarta.servlet since Jakarta EE 9; older code uses javax.servlet, with the same API.)

Describe the servlet lifecycle.

The container loads the class and creates one instance, calls init(ServletConfig) once, then calls service() on that instance for every request (each request on its own thread), and finally calls destroy() once when the servlet is unloaded or the application stops. Because one instance serves many threads, instance fields must not hold per-request data. See Servlet Lifecycle and Deployment.

What is the difference between doGet and doPost?

GET asks for a resource: parameters travel in the URL's query string, the request is safe and idempotent (it must not change server state), and responses can be cached and bookmarked. POST sends data in the request body to create or change something, is not idempotent, is not cached, and is the right choice for forms that change data and for anything private or large. Never put passwords in a GET URL, because URLs end up in logs and history. See Servlet Requests and Forms.

What is the difference between forward and sendRedirect?

RequestDispatcher.forward(req, res) happens inside the server: the same request (and its attributes) is handed to another servlet or JSP, the browser's URL does not change, and the browser knows nothing about it. response.sendRedirect(url) sends a 302 response with a Location header, so the browser makes a new request to that URL: the address bar changes, request attributes are lost, and it can go to another application or site. Use forward to pass data to a view; use sendRedirect after a successful POST (the Post-Redirect-Get pattern) so a refresh does not resubmit the form.

What is a RequestDispatcher, and what is the difference between forward and include?

A RequestDispatcher wraps a server resource (obtained from request.getRequestDispatcher(path) or ServletContext.getRequestDispatcher(path)). With forward, control passes completely to the target, which produces the whole response. With include, the target's output is inserted into the current response and control returns to the caller, so the calling servlet can keep writing. forward fails with IllegalStateException if the response was already committed.

What are ServletConfig and ServletContext?

ServletConfig is per servlet: it carries the servlet's own init-param values and its name. ServletContext is per web application: one object shared by every servlet, filter and JSP in the app. It offers application-wide init-param values (<context-param>), shared attributes (setAttribute/getAttribute), getRealPath, getResourceAsStream, logging and the ability to get dispatchers. Anything stored in it is visible to all users, so it must be thread-safe.

What is the role of web.xml, and can you do without it?

web.xml is the deployment descriptor in WEB-INF/. It declares servlets, URL mappings, filters, listeners, init parameters, welcome files, error pages and security constraints. Since Servlet 3.0 most of that has annotations (@WebServlet, @WebFilter, @WebListener) and programmatic registration, so web.xml is optional; it is still useful for settings that should change without recompiling, and it overrides annotations. Spring Boot with an embedded container has neither: you register servlets as beans.

How do you read request parameters and send JSON?

request.getParameter("name") returns the first value of a form or query parameter as a String (or null), getParameterValues returns all of them, and getParameterMap returns everything. For a JSON body you read request.getReader() or getInputStream() and parse it with a library such as Jackson. To answer with JSON set response.setContentType("application/json"), set the character encoding (UTF-8), and write the text with response.getWriter(). Set the status with setStatus and headers with setHeader before writing the body.

Sessions and state

What is a session, and how does the container track one?

HTTP is stateless, so the server gives each browser a session: an HttpSession object held on the server, identified by a random id. The id is sent to the client in a cookie named JSESSIONID and comes back with every request. request.getSession() returns the current session, creating one if none exists (getSession(false) returns null instead). You store data with setAttribute and read it with getAttribute, and invalidate() ends the session (the logout action). The inactivity timeout is set with setMaxInactiveInterval or <session-timeout>. See Sessions and Cookies.

What is a cookie, and what are its limits?

A cookie is a small name/value pair the server asks the browser to store (Set-Cookie) and send back on later requests to the same site. In a servlet: response.addCookie(new Cookie("theme", "dark")) and request.getCookies(). Limits: about 4 KB each, sent with every request (so keep them small), visible to and editable by the user, so never store secrets or trust their value. Security attributes to set: HttpOnly (hidden from JavaScript), Secure (HTTPS only), SameSite, and a path and max age.

What is URL rewriting, and when is it used?

URL rewriting is session tracking without cookies: the session id is appended to every URL as a path parameter, for example /cart;jsessionid=9F2C.... A servlet produces such links with response.encodeURL(url) (and encodeRedirectURL for redirects), which adds the id only when the container cannot tell that cookies work. It was meant for browsers with cookies disabled. Today it is rarely used and considered a security risk, since session ids leak through logs, the Referer header and shared links; modern containers disable it by default.

What other ways exist to keep state between requests?

Cookies, URL rewriting, hidden form fields (state is carried in the form itself), the session (server-side), and for stateless designs a token such as a JWT that the client sends in a header. Cookies and hidden fields keep state on the client and must be validated, the session keeps it on the server and must be shared or made sticky when you run several instances.

What is the difference between session, request and application scope?

They are the lifetimes of attributes. Request scope lives for one request (including forwards). Session scope lives for one user across requests until it expires. Application scope (ServletContext) lives as long as the web application and is shared by everyone. JSP adds a fourth, page scope, for one JSP page only. Use the smallest scope that works; large session objects cost memory per user, and application scope needs thread safety.

Filters and listeners

What are servlet filters, and when do you use them?

A filter is an object that sits in front of a servlet (or static resource), able to inspect or change the request, short-circuit it, and wrap the response. A filter chain is built from the URL patterns; each filter calls chain.doFilter(req, res) to pass control on. Typical uses: authentication and authorization checks, logging and timing, character-encoding settings, compression, CORS headers, and rate limiting. In Spring MVC a HandlerInterceptor serves a similar purpose one level deeper. See Filters and Listeners.

What are servlet listeners?

Listeners react to events in the container: ServletContextListener (application start and stop, good for creating a connection pool or loading configuration), HttpSessionListener (session created or destroyed, for counting active users), ServletRequestListener (each request), and the attribute listeners (...AttributeListener), which fire when attributes are added, replaced or removed. Register them with @WebListener or web.xml.

JSP questions

What is JSP, and why was it created?

JavaServer Pages let you write HTML with embedded Java and tags, so a page author can build a view without writing out.println for every line. The container translates each JSP into a servlet class on first use, compiles it and runs it like any servlet, so a JSP is a servlet with a friendlier syntax. Advantages: easy templates, tag libraries (JSTL), automatic recompilation on change, and the full servlet platform underneath. Today it is mostly legacy, with Thymeleaf and component frameworks preferred for new work. See JSP.

What is the JSP lifecycle?
  1. Translation: the JSP becomes a servlet source file. 2. Compilation to a class. 3. Loading and instantiation. 4. jspInit(), once. 5. _jspService(request, response) for every request (generated from your page; you never write it). 6. jspDestroy(), once, when the page is unloaded. Translation and compilation happen on the first request (or at deployment), so the first hit after an edit is slower.
What are the types of JSP directives?

There are three. page sets page-wide options (import, contentType, session, errorPage, isErrorPage, isELIgnored). include pastes another file in at translation time. taglib declares a tag library and its prefix (<%@ taglib prefix="c" uri="jakarta.tags.core" %>). All start with <%@.

What are scriptlets, expressions and declarations?

Three scripting elements: a scriptlet <% ... %> is Java statements placed inside _jspService; an expression <%= value %> writes a value to the output; a declaration <%! ... %> adds fields or methods to the generated class (shared by all requests, so not thread-safe). Scriptlets are discouraged: they mix logic and markup and are hard to test. Prefer EL (${...}) and JSTL tags, and keep logic in servlets or controllers.

What are the JSP implicit objects?

Objects available in every scriptlet without declaring them: request, response, out (the JspWriter), session, application (the ServletContext), config (ServletConfig), pageContext (access to all scopes and the other implicit objects), page (the servlet itself, this), and exception (only on pages marked isErrorPage="true"). In EL there is a separate set: pageScope, requestScope, sessionScope, applicationScope, param, paramValues, header, cookie, initParam and pageContext.

What are the JSP scopes, and in what order does ${name} search them?

The four scopes are page, request, session and application. An unqualified ${name} searches them in that order, narrowest first, and returns the first match. A qualified form such as ${sessionScope.name} looks in one scope only, which avoids surprises when two scopes have the same attribute name.

How do you handle exceptions in a JSP?

Mark a normal page with <%@ page errorPage="/error.jsp" %>; any uncaught exception forwards to that page. The error page declares <%@ page isErrorPage="true" %> and then has the exception implicit object. Application-wide, <error-page> in web.xml maps exception types and status codes (404, 500) to pages. In a modern app, catch exceptions in the controller layer and return a proper error view rather than letting them reach the JSP.

What is the difference between jsp:include and the include directive?

The directive <%@ include file="..." %> pastes the other file at translation time, producing one servlet that shares variables; <jsp:include page="..."/> runs the other page at request time as its own servlet and inserts its output. Use the directive for static fragments (headers, taglib declarations), the action for dynamic content. See the comparison table in JSP.

What is JSTL, and why prefer it over scriptlets?

The JSP Standard Tag Library supplies tags for common tasks: c:if, c:choose, c:forEach, c:out (with escaping), c:url, formatting (fmt:formatDate, fmt:formatNumber), SQL and XML helpers, and functions such as fn:length. Together with EL they let designers write loops and conditions without Java code, produce HTML that is easier to read, and avoid XSS by escaping with c:out. See JSTL and Expression Language.

Two runnable models

Both programs are stand-ins for container behavior: plain Java that behaves the way the container does.

The first shows session tracking. The "container" issues a JSESSIONID, reads it from a cookie, and falls back to the id in the URL (URL rewriting) when the client sends no cookie:

Java Session id from a cookie, or from the URL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second shows the scope lookup of an unqualified EL name, and why a qualified name is safer:

Java How ${name} searches page, request, session, application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A servlet saves an order and then wants the browser to show a confirmation page, so that pressing Refresh does not submit the order again. What should it call?

    A redirect makes the browser issue a new GET request (Post-Redirect-Get). After a forward the browser would still be on the POST result, and refreshing would resubmit it.
  2. 2. Which statement about ServletConfig and ServletContext is correct?

    Each servlet gets its own ServletConfig. There is one ServletContext for the whole application, shared by all servlets, filters and JSPs.
  3. 3. A user has cookies disabled. How can the container still track the session?

    URL rewriting appends the session id (;jsessionid=...) to links. It works without cookies but leaks the id easily and is now disabled by default.
  4. 4. Which JSP directive pastes another file in at translation time?

    The include directive is resolved when the page is translated. The jsp:include action is an action tag that runs at request time.
  5. 5. In a JSP, ${user} is found in both request and session scope. Which value is used?

    Unqualified names are searched page, request, session, application. Use sessionScope.user to pick one explicitly.

Summary

  • A servlet container creates one servlet instance and calls init, service (per request, per thread) and destroy; HttpServlet routes service to doGet, doPost and the other methods.
  • forward is internal to the server and keeps the request; sendRedirect sends a 302 and the browser makes a new request.
  • ServletConfig is per servlet, ServletContext per application; session data lives on the server, identified by a JSESSIONID cookie or a rewritten URL.
  • Filters wrap requests, listeners observe container events; both are alternatives to repeating code in every servlet.
  • A JSP is translated into a servlet: three directives (page, include, taglib), scripting elements, implicit objects and four scopes. Prefer EL and JSTL over scriptlets.

Next: Advanced Java Interview Questions covers JDBC, JPA, Spring and microservices.