JSP and servlet interview questions and answers
JSP interview questions check that you understand how a server page becomes a servlet, how its life cycle runs, and how to build views with Expression Language and JSTL instead of Java scriptlets. Expect questions on the implicit objects, the four scopes, include directive versus include action, forward versus redirect, and session handling. Many roles that ask about JSP are maintaining older Java web apps, so answers about safe escaping and gradual migration carry weight.
By Evin JohnPublished 8 min read
Where JSP still shows up
New Java projects rarely start with JSP, yet plenty of banking portals, insurance back offices, telecom self-care sites and internal tools still run on it, usually on Tomcat or a full Jakarta EE server. Interviews for those teams, for Java developer roles at service companies, and for campus placements that follow an advanced Java syllabus still include JSP and servlet questions. The candidate who can explain the mechanics and also talk about making an old app safer stands out.
- Theory roundLife cycle, directives, implicit objects and scopes, often as rapid-fire questions.
- Read a pageA JSP with scriptlets and EL: what does it print, where is the bug, what is unsafe?
- Servlet and MVCHow a request reaches a servlet, how data is passed to the view, and how navigation works.
- Maintenance scenarioSession bugs, a slow page, an XSS report or a plan to migrate to a modern template engine or front end.
JSP fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is JSP? | Basics | A template technology where HTML is mixed with special tags and expressions. The container turns each page into a servlet. The spec is now called Jakarta Server Pages. |
| Describe the JSP life cycle. | Life cycle | Translation of the page into servlet source, compilation, class loading, instantiation, jspInit once, _jspService for every request, and jspDestroy when the page is taken out of service. |
| Which life cycle methods can you override? | Detail | jspInit and jspDestroy, through a declaration. _jspService is generated from the page body and should not be overridden. |
| What are the three directives? | Directives | page (imports, content type, error page, session use), include (static inclusion at translation time) and taglib (declares a tag library and its prefix). |
| Scriptlet, expression and declaration? | Scripting elements | <% %> holds Java statements run per request, <%= %> prints a value, <%! %> declares fields or methods on the generated servlet class. |
| Name the implicit objects. | Implicit objects | request, response, out, session, application, config, pageContext, page and exception. exception exists only on pages marked isErrorPage="true". |
| What are the four scopes? | Scopes | Page (this page only), request (across a forward or include in one request), session (one user across requests) and application (shared by the whole web app). |
| JSP comment versus HTML comment? | Output | <%-- --%> is removed during translation and never reaches the browser. An HTML comment is sent to the client and visible in the page source. |
| What is the difference between a JSP and a servlet? | Roles | Both end up as servlets. JSP suits views where markup dominates; servlets suit control logic. In MVC the servlet handles the request and the JSP renders the result. |
| How does the container know a JSP changed? | Development | Containers such as Tomcat can check the file timestamp and retranslate in development mode. Production setups often precompile pages and turn checking off. |
Intermediate questions: EL, JSTL and navigation
<%@ page contentType="text/html; charset=UTF-8" session="false" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<h1>Orders for <c:out value="${customer.name}"/></h1>
<c:choose>
<c:when test="${empty orders}">
<p>No orders yet.</p>
</c:when>
<c:otherwise>
<table>
<c:forEach var="o" items="${orders}" varStatus="s">
<tr class="${s.index % 2 == 0 ? 'even' : 'odd'}">
<td><c:out value="${o.reference}"/></td>
<td><fmt:formatDate value="${o.placedAt}" pattern="yyyy-MM-dd"/></td>
<td><c:out value="${o.status}"/></td>
</tr>
</c:forEach>
</table>
</c:otherwise>
</c:choose>- What is Expression Language? The
${...}syntax for reading attributes, bean properties, map entries and request parameters without Java code. It searches page, request, session and application scope in that order when a name is not qualified. - Why does the page use c:out instead of printing the EL directly? c:out escapes HTML special characters by default. A bare EL expression in template text, or a
<%= %>expression, writes the raw value, which is an XSS hole for anything that came from a user. - What is JSTL? The standard tag library: core tags for conditions, loops, URLs and variables, fmt for numbers, dates and messages, fn for string functions, plus sql and xml tags that rarely belong in a view.
- Which taglib URI should you use? It depends on the version. Older apps use the java.sun.com URIs with javax packages; newer Jakarta versions use the jakarta.tags URIs. Mixing them is a common migration error, so match the JSTL jar to the container.
- Include directive versus jsp:include? The directive copies the file's source into the page at translation time, so it shares variables and changes need retranslation. The action includes the other resource's output at request time, so it can be dynamic.
- Forward versus redirect? A forward (jsp:forward or RequestDispatcher.forward) hands the same request to another resource on the server; the browser URL does not change and request attributes survive. A redirect sends a 302 or 303 so the browser makes a new request, losing request attributes.
- When must you redirect after a form post? After a successful POST, redirect to a GET page (the post-redirect-get pattern) so a browser refresh does not resubmit the form.
- How do you handle errors in JSP? Set errorPage on a page or, better, declare error pages by status code or exception type in web.xml, and log the exception on the server instead of showing a stack trace.
- What does session="false" do? Stops the page from creating a session just because it was viewed. Pages that do not need one should say so, since sessions cost memory.
- How do you write a custom tag? Simple tag files (
.tag) for markup reuse, or a class extending SimpleTagSupport described in a TLD for logic. Both keep Java out of the page.
Servlets and MVC questions
@WebServlet("/orders")
public class OrderListServlet extends HttpServlet {
private OrderService orders; // created once in init, shared by all requests
@Override
public void init() {
orders = (OrderService) getServletContext().getAttribute("orderService");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
long customerId = Long.parseLong(req.getParameter("customer"));
req.setAttribute("customer", orders.customer(customerId));
req.setAttribute("orders", orders.recentFor(customerId));
req.getRequestDispatcher("/WEB-INF/views/orders.jsp").forward(req, resp);
}
}| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why put JSPs under WEB-INF? | Structure | Files under WEB-INF cannot be requested directly, so users must go through the controller that prepares the data and checks access. |
| What is Model 2 architecture? | MVC | A servlet acts as controller, plain objects or services as model, and JSP as view. Front controller frameworks such as Spring MVC grew from this pattern. |
| How many instances of a servlet does the container create? | Threading | Normally one per declaration. Every request runs on its own thread through the same instance, which is why instance fields must not hold per-request data. |
| Why are JSP declarations a threading risk? | Thread safety | A variable declared with <%! %> becomes a field shared by every request, so two users can overwrite each other's values. Keep request data in local variables or request attributes. |
| How is a session tracked? | Sessions | Usually with a JSESSIONID cookie, falling back to URL rewriting with encodeURL when cookies are off. The session data lives on the server. |
| What belongs in a session? | Design | Small, serializable data such as the user's identity and a few preferences. Large objects hurt memory and replication; sensitive data needs care, and the ID should change at login. |
| What is a filter used for? | Cross-cutting work | Code that runs before and after servlets for many URLs: authentication checks, logging, compression, character encoding and security headers. |
| What is a ServletContextListener? | App startup | A hook that runs when the web app starts and stops, used to create shared services such as a connection pool and to close them cleanly. |
Senior and maintenance scenarios
- A penetration test reports reflected XSS on a search page. What do you fix? Find every place user input is written with
<%= %>or bare EL and switch to c:out or the fn:escapeXml function, set a Content Security Policy, and add a test with a script payload. Encoding must match the context: HTML body, attribute, JavaScript or URL. - How would you protect forms against CSRF in a plain JSP app? A per-session token stored server-side, rendered into a hidden field, and checked by a filter on every state-changing request, plus SameSite cookies.
- Users sometimes see each other's data. Where do you look? Shared mutable state: servlet instance fields, JSP declarations, static caches keyed wrongly, or data put in application scope instead of session or request scope.
- The first request after each deploy is slow. Why? Pages are translated and compiled on first access. Precompile them during the build so the container loads ready classes.
- Pages are full of scriptlets with SQL in them. How do you improve the app without a rewrite? Move data access into DAO or service classes, have servlets set request attributes, and replace scriptlets with EL and JSTL one page at a time, adding tests around each change.
- How would you move from javax to jakarta? Upgrade to a container that supports the jakarta namespace, update imports, deployment descriptors and JSTL URIs, and use migration tooling where it helps. Test every page, since tag library mismatches fail only at runtime.
- JSP or a modern alternative for new work? For server-rendered pages, template engines such as Thymeleaf integrate better with Spring Boot, which documents limitations for JSP in executable jars. Many teams instead serve JSON from Java and build the UI separately.
Fictional example
- Interviewer
- The page declares a counter with <%! int hits = 0; %>, opens a JDBC connection in a scriptlet, and prints the search term with <%= request.getParameter("q") %>. Your review?
- Candidate
- Three issues, most serious first. The search term is printed unescaped, which is reflected XSS; I would output it with c:out. The hits counter is a field on the generated servlet, shared by every request, so increments race and the number is wrong under load; if it matters, use an AtomicLong in a service or real metrics. And the page opens its own database connection, which mixes data access into the view and probably leaks connections on errors. I would move that into a DAO using a pooled DataSource, call it from a servlet, and forward to this page with request attributes only.
JSP practice plan
- Day 1: write out the life cycle and the nine implicit objects from memory, then explain each scope with an example of what belongs there.
- Day 2: in a local Tomcat project, build one servlet and one JSP view, then open the generated servlet source the container wrote for your page.
- Day 3: convert a scriptlet-heavy page to EL and JSTL, and prove the escaping works by submitting a script tag as input.
- Day 4: add a filter for authentication and a CSRF token, then explain both aloud in two minutes each.
- Day 5: rehearse the maintenance scenarios, ending each with how you would test the fix.
For the wider Java loop, see Java developer interview questions. Spring Boot interview questions covers what most JSP apps migrate to, and JSON interview questions helps if the new front end talks to your Java code through an API. Load testing an old JSP portal before a migration is covered in JMeter interview questions.
Legacy-code questions reward a calm, ordered review, which is easy to lose under pressure. Natively, an AI interview assistant for Mac and Windows, transcribes your practice session on the computer, so you can check whether you ranked the XSS issue above the style issues. In practice it can read a JSP from a screenshot and suggest review points, and with Pro or the free trial it brings in the résumé and job description you add. The transcript and notes are there to revisit.
Questions people ask
What JSP questions are asked in interviews?
The JSP life cycle, directives, scriptlets versus expressions versus declarations, implicit objects, the four scopes, EL and JSTL, include directive versus include action, forward versus redirect, and session tracking.
What is the JSP life cycle?
The container translates the page into a servlet, compiles and loads it, calls jspInit once, _jspService for every request, and jspDestroy when the page is removed from service.
What is the difference between forward and sendRedirect?
A forward passes the same request to another resource on the server, so the URL stays and request attributes survive. A redirect makes the browser send a new request to a new URL.
How many implicit objects does JSP have?
Nine: request, response, out, session, application, config, pageContext, page and exception, which exists only on error pages.
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.
