A page hits.jsp is requested 3 times. The developer then edits the file. It is requested 2 more times and the server is then shut down. How many times do translation, compilation, jspInit, _jspService and jspDestroy run in total?
Servlets are Java classes that a web container runs to answer HTTP requests; JSP lets you write the same thing as an HTML-like page that the container turns into a servlet. Life cycles, JSP syntax, the nine implicit objects, forward vs redirect and sessions are all exam staples.
<%@ include file=… %> merges text at translation time; <jsp:include page=… /> runs the resource at request time. <%! %> declarations become class members and are shared by all threads.A static web page is a file; a dynamic page is produced by a program each time it is requested — a list of housing schemes read from a database, a status page for one applicant. The oldest way to run such a program was CGI (Common Gateway Interface): the web server starts a brand-new operating-system process for every request, the program prints HTML and the process ends. Starting a process is slow, and a busy site pays that cost thousands of times a minute.
A servlet is a Java class that extends the web server's abilities. A web container (also called a servlet container or servlet engine; Apache Tomcat is the best-known free one, and Jetty, GlassFish and WildFly are others) loads the class once, creates a single instance and hands every incoming request to a new thread of that instance. Threads are far cheaper than processes, the instance stays in memory (it is persistent) and, being Java, the same class runs on any operating system.
The container is more than a thread pool. It parses the HTTP request into HttpServletRequest and HttpServletResponse objects, maps URLs to servlets, manages sessions, enforces declarative security, and compiles JSPs. A web application is packaged as a WAR file (Web ARchive) whose layout is fixed: public files (HTML, JSP, images) at the top, and a protected WEB-INF folder holding web.xml (the deployment descriptor), classes/ for compiled classes and lib/ for JAR files. Anything under WEB-INF cannot be fetched directly by a browser.
javax.servlet. When the project moved to the Eclipse Foundation as Jakarta EE, the packages were renamed to jakarta.servlet from Jakarta EE 9 (Servlet 5.0, Pages 3.0). Tomcat 9 and older run javax.* code; Tomcat 10 and newer need jakarta.*. Older textbooks and most past papers still write javax.servlet.Every servlet implements the Servlet interface, which declares five methods: init, service, destroy, getServletConfig and getServletInfo. In practice you extend HttpServlet (a subclass of GenericServlet, which is protocol-independent) and override only the HTTP methods you need. The container drives the life cycle; your code never calls these methods itself.
load-on-startup can move it to server start-up.ServletConfig holding the servlet's init parameters. Open shared resources here. If it throws an exception, the servlet is not put into service.HttpServlet.service looks at the HTTP method and dispatches to doGet, doPost, doPut, doDelete, doHead, doOptions or doTrace.init opened.The default doGet and doPost of HttpServlet reply with 405 Method Not Allowed, so a servlet answers only the methods it overrides. Use GET for reading data (parameters travel in the URL, the request can be bookmarked and repeated safely) and POST for changes (parameters are in the body, the amount is not limited by URL length). Try the Thread, applet, servlet/JSP & ASP.NET lifecycles tool on this page — it opens on the Servlet & JSP tab, where you can see init run once and service run for each request.
| Method | Called | Times | Typical use |
|---|---|---|---|
init(ServletConfig) | After instantiation, before any request | Once | Read init parameters, create or look up a connection pool |
service() → doGet/doPost | For every request | Many, concurrently | Read the request, produce the response |
destroy() | Before the instance is removed | Once | Release connections, flush logs |
Thread-safety follows directly. There is one instance, so its fields (instance variables) are shared by all request threads. A servlet that stores per-request data in a field will mix up users when two requests overlap. Keep per-request data in local variables and request attributes; make fields read-only after init, or guard changes with synchronized. The old marker interface SingleThreadModel tried to serialise requests but was deprecated for years and removed in Servlet 6.0; do not use it.
If you override init(ServletConfig config), call super.init(config) first, otherwise getServletConfig() returns null. The simpler habit is to override the no-argument init(), which GenericServlet calls after storing the config.
<load-on-startup> (or loadOnStartup in the annotation) with a value of zero or more asks the container to create the servlet at start-up, lower numbers first; a negative or missing value lets it load lazily on the first request. A servlet is mapped to URLs either in web.xml with <servlet> and <servlet-mapping>, or since Servlet 3.0 with the @WebServlet annotation. The annotation needs no XML, but web.xml entries override it.<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" version="6.0">
<servlet>
<servlet-name>apply</servlet-name>
<servlet-class>kshb.ApplyServlet</servlet-class>
<init-param>
<param-name>office</param-name>
<param-value>Thiruvananthapuram</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>apply</servlet-name>
<url-pattern>/apply</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>Each call to service receives two objects. HttpServletRequest describes what the browser sent; HttpServletResponse is where you build the reply.
| Object | Important methods | What they do |
|---|---|---|
HttpServletRequest | getParameter(name) | Value of one form field or query parameter as a String; null if the parameter is absent, empty string if present but blank |
getParameterValues(name) | All values of a repeated name (check-boxes, multi-selects) as String[] | |
getParameterNames(), getParameterMap() | All names / the whole map | |
getHeader(name), getMethod(), getCookies() | Headers, HTTP method, cookies sent by the browser | |
getSession(), getSession(false) | Current session (created if missing) / current session or null | |
setAttribute, getAttribute, getRequestDispatcher(path) | Request-scope data and a handle to forward or include another resource | |
HttpServletResponse | setContentType("text/html;charset=UTF-8") | MIME type and encoding — call it before getting the writer |
getWriter() / getOutputStream() | PrintWriter for text / ServletOutputStream for binary data; use only one of them per response | |
setStatus(code), sendError(code, msg) | Set a status / send an error page | |
sendRedirect(url), addCookie(c), setHeader(n, v) | Redirect the browser, send a cookie, add a header |
Here is a small servlet that handles a form. It uses the Jakarta package names; with Tomcat 9 or older replace jakarta by javax.
<form action="apply" method="post">
<label>Name <input name="name" required></label>
<label><input type="checkbox" name="scheme" value="A"> Scheme A</label>
<label><input type="checkbox" name="scheme" value="B"> Scheme B</label>
<button>Submit</button>
</form>package kshb;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/apply", loadOnStartup = 1)
public class ApplyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8"); // before reading any parameter
String name = req.getParameter("name"); // null if the field is absent
String[] schemes = req.getParameterValues("scheme");
if (name == null || name.isBlank()) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Name is required");
return; // nothing more to write
}
int count = (schemes == null) ? 0 : schemes.length;
resp.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.println("<html><body>");
out.println("<h1>Application received</h1>");
out.println("<p>Schemes chosen: " + count + "</p>");
out.println("</body></html>");
}
}
}request.getParameter("fieldName") returns the value as a String. getParameterNames() returns only an Enumeration of names, and there is no getValues or putValues. To read a redirect target, remember response.sendRedirect(url) — it is the response that redirects; request.sendRedirect() and response.forward() do not exist.A servlet often does not produce the final page itself. It prepares data and hands over to another resource, usually a JSP. There are three ways to hand over, and the difference is a certain exam question.
RequestDispatcher.forward | RequestDispatcher.include | response.sendRedirect | |
|---|---|---|---|
| Who acts | Server, inside the container | Server, inside the container | Browser, told by the server |
| Browser requests | 1 | 1 | 2 (second one is automatic) |
| URL in address bar | Unchanged | Unchanged | Changes to the new URL |
| Request and its attributes | Shared with target | Shared with target | Lost (a new request) |
| Control returns to caller | No — target writes the response | Yes — caller continues | Not applicable |
| Target may be outside this web app | Normally no (same web app) | Normally no | Yes — any URL |
@WebServlet("/schemes")
public class SchemeListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
List<String> schemes = List.of("Scheme A", "Scheme B", "Scheme C");
req.setAttribute("schemes", schemes); // request scope
req.getRequestDispatcher("/WEB-INF/views/schemes.jsp")
.forward(req, resp); // URL stays /schemes
}
}forward throws IllegalStateException if the response has already been committed (sent to the browser), and any text written to the buffer before the forward is discarded. Use forward after processing a form to display a result inside the same request; use sendRedirect after a POST that changes data, so a browser refresh repeats a harmless GET instead of re-submitting the form (the post-redirect-get pattern).Two configuration objects are easy to mix up. ServletConfig is created per servlet and holds that servlet's own init parameters (<init-param>). ServletContext is created once per web application and is shared by all its servlets and JSPs: it holds context parameters (<context-param>), lets you read resources, write to the log and store application-wide attributes. In a servlet you obtain it with getServletContext(); in a JSP it is the implicit object application.
| Scope | Lives as long as | Object / JSP name | Typical content |
|---|---|---|---|
| Page | One page (one _jspService call) | pageContext | Loop variable, temporary value (JSP only) |
| Request | One request, including forwards and includes | request | Data a controller passes to a view |
| Session | One user, from first visit until timeout or logout | session | Logged-in user, shopping cart |
| Application | Until the web application stops | application (ServletContext) | Shared settings, a connection pool, a hit counter |
All four scopes offer setAttribute(name, value), getAttribute(name) and removeAttribute(name). Choose the narrowest scope that works: wider scopes cost memory, live longer and — for session and application — are visible to several threads, so they need care with concurrent updates.
Writing HTML with out.println("...") inside Java is painful. JavaServer Pages (JSP) reverses the arrangement: you write an ordinary HTML page and insert small pieces of Java or tags where the content is dynamic. A JSP is not run directly. On the first request the container's JSP engine (Jasper in Tomcat) converts it into a servlet class, compiles it and from then on treats it like any other servlet. So a JSP is a servlet — only the way it is written differs.
apply.jsp into Java source, for example apply_jsp.java. Template text becomes out.write(...) calls; scriptlets are copied; expressions become out.print(...). Syntax errors in directives are caught here.apply_jsp.class. Java errors inside scriptlets show up at this stage.init(). You may override it in a declaration.The generated class implements HttpJspPage (usually by extending a container class such as Tomcat's HttpJspBase, itself an HttpServlet). Translation and compilation are the expensive steps, so they happen only once per version of the page. On each request the container compares the page's modification time with what it translated; if the .jsp file was edited, it translates and compiles again, loads the new class and calls jspDestroy on the old one. Pages included by the include directive are tracked too. Sites that dislike the first-hit delay can precompile their JSPs at build time.
| Servlet | JSP equivalent | Runs |
|---|---|---|
init() | jspInit() | Once |
service() | _jspService() | Every request |
destroy() | jspDestroy() | Once |
| Java code with embedded HTML strings | HTML with embedded Java / tags | — |
JSP has three families of constructs. Directives (<%@ … %>) give the engine instructions at translation time. Scripting elements (declarations, scriptlets, expressions) embed Java. Standard actions (<jsp:… />) are XML-style tags that act at request time.
| Directive | Purpose | Notable attributes (default) |
|---|---|---|
<%@ page … %> | Properties of this page | import, contentType (text/html; charset ISO-8859-1 unless a charset or pageEncoding is given), session (true), errorPage, isErrorPage (false), buffer (at least 8kb), autoFlush (true), isELIgnored, isThreadSafe (true; deprecated in Pages 3.1) |
<%@ include file="x.jspf" %> | Copy another file's text into this page at translation time | file |
<%@ taglib uri="…" prefix="c" %> | Make a tag library available | uri (or tagdir), prefix |
| Element | Syntax | Becomes in the generated class |
|---|---|---|
| Declaration | <%! int visits = 0; %> | A field or method of the servlet class — shared by all requests |
| Scriptlet | <% int n = 5; %> | Statements inside _jspService — local to each request |
| Expression | <%= visits %> | out.print(visits); — no semicolon in the tag |
| JSP comment | <%-- note --%> | Dropped; never reaches the browser |
| HTML comment | <!-- note --> | Template text, so it is sent to the browser |
<%@ page contentType="text/html;charset=UTF-8" import="java.time.LocalDate" session="true" %>
<%@ include file="header.jspf" %>
<%!
private int visits = 0; // instance variable: shared
private String today() { return LocalDate.now().toString(); }
%>
<%
int mine; // local: one per request
synchronized (this) { visits++; mine = visits; }
%>
<%-- This comment is removed during translation --%>
<!-- This comment is sent to the browser -->
<p>Date: <%= today() %> | you are visitor number <%= mine %></p>
<p>New session? <%= session.isNew() %></p><%! %> belongs to the single servlet instance, so concurrent requests all touch it and it keeps its value between requests (and resets only when the page is re-translated). A variable declared in a <% %> scriptlet is a local variable of _jspService and is created afresh for every request. Methods you declare can be called from scriptlets, and jspInit / jspDestroy can be overridden here.<jsp:param><%@ include %> directive. <jsp:include> works at request time. Likewise <jsp:forward page="…" /> is the action form of RequestDispatcher.forward.The standard actions you must know: jsp:include (insert output), jsp:forward (hand the request to another resource), jsp:param (a name/value pair nested inside include or forward), and the three bean actions. A JavaBean is a plain Java class that follows conventions: a public no-argument constructor, private properties exposed through getX() / setX() methods (isX() for booleans) and usually implements Serializable. Because of the no-argument constructor, the container can create beans by itself.
package kshb;
import java.io.Serializable;
public class Applicant implements Serializable {
private String name;
private int age;
public Applicant() { } // public no-argument constructor
public String getName() { return name; }
public void setName(String n) { this.name = n; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}<jsp:useBean id="app" class="kshb.Applicant" scope="request" />
<jsp:setProperty name="app" property="*" /> <%-- copy matching request parameters --%>
<p>Name: <jsp:getProperty name="app" property="name" /></p>
<jsp:include page="footer.jsp">
<jsp:param name="year" value="2026" />
</jsp:include>jsp:useBean looks for an object called id in the given scope (page by default; request, session or application) and creates a new one if none exists. jsp:setProperty with property="*" matches every request parameter to a setter of the same name and converts numbers automatically; jsp:getProperty writes a property into the output.
Inside scriptlets and expressions you can use certain variables without declaring them, because the engine declares them at the top of _jspService. These are the implicit objects. There are exactly nine.
| Object | Type | Role | Scope |
|---|---|---|---|
request | HttpServletRequest | Incoming request: parameters, headers, cookies | Request |
response | HttpServletResponse | Outgoing response: status, headers, cookies, redirect | Page |
out | JspWriter | Buffered writer for the page body (like PrintWriter but buffered) | Page |
session | HttpSession | Per-user data (not available if session="false") | Session |
application | ServletContext | Web-application-wide data and resources | Application |
config | ServletConfig | This JSP's init parameters | Page |
pageContext | PageContext | Gateway to all other objects and to all four scopes | Page |
page | Object (the this reference) | The generated servlet itself; rarely used | Page |
exception | Throwable | The uncaught error; only in pages with isErrorPage="true" | Page |
application.Error handling uses two attributes of the page directive. A page that may fail names an error page with errorPage="oops.jsp"; the error page declares isErrorPage="true" and can then use exception. Ordinary pages cannot see exception — using it there is a compile error. The same job can be done for the whole application with <error-page> entries in web.xml that map status codes (404, 500) or exception classes to pages.
<%@ page isErrorPage="true" contentType="text/html;charset=UTF-8" %>
<h1>Something went wrong</h1>
<p>Type: <%= exception.getClass().getName() %></p>pageContext is the Swiss-army object: pageContext.setAttribute(name, value, PageContext.SESSION_SCOPE) stores in any scope, findAttribute(name) searches page, request, session and application in that order, and pageContext.forward(...) / include(...) dispatch like a RequestDispatcher.
HTTP is stateless, so a servlet application must recognise a returning user by itself. The common techniques are cookies (a name/value pair stored by the browser and sent back with every request), hidden form fields, URL rewriting (the session id is appended to links) and the HttpSession object that wraps them for you.
When code calls request.getSession(), the container creates a session (if none exists), stores it on the server under a random id and sends that id in a cookie named JSESSIONID. The browser returns the cookie with later requests and the container finds the same HttpSession again. If cookies are disabled, the container falls back to URL rewriting: you pass every link through response.encodeURL(url) (and redirects through encodeRedirectURL), which appends ;jsessionid=… only when needed.
| Technique | Stored where | Notes |
|---|---|---|
| Cookie | Browser | new Cookie(n, v), setMaxAge(seconds), response.addCookie(c); read with request.getCookies(); about 4 KB, text only |
| Hidden field | In the HTML form | <input type="hidden">; survives only form submissions |
| URL rewriting | In the link | encodeURL(); works without cookies; ids appear in URLs |
HttpSession | Server memory; only the id travels | Holds any Java object; shared by all requests of one user |
HttpSession session = request.getSession(); // create if missing
session.setAttribute("user", "anil"); // store
String user = (String) session.getAttribute("user"); // read (needs a cast); null if absent
session.setMaxInactiveInterval(15 * 60); // seconds of idleness allowed
// ...at logout
session.invalidate(); // remove the session and its data<session-timeout> in web.xml is in minutes (container default 30 — the figure usually quoted), but setMaxInactiveInterval(int) takes seconds. In Servlet 6.0 a value of zero or less means the session never expires; older books mention only negative values, so a negative number is the portable way to say "never". The 30-minute default is set by the container (Tomcat's own web.xml), not fixed by the specification. Each request resets the idle clock. getSession(false) returns null instead of creating a session, which is what a login check wants.A typical form → servlet → database flow ties everything together: a JSP or HTML page posts a form; a servlet reads the parameters, runs SQL through JDBC (Java Database Connectivity), stores a result or message in a scope and either forwards to a JSP or redirects. The JDBC steps are always: (1) load/register the driver, (2) get a Connection, (3) create a statement, (4) execute it, (5) process the ResultSet or update count, (6) close everything.
package kshb;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@WebServlet(urlPatterns = "/save", initParams = {
@jakarta.servlet.annotation.WebInitParam(name = "dbUrl", value = "jdbc:mysql://localhost:3306/housing"),
@jakarta.servlet.annotation.WebInitParam(name = "dbUser", value = "app") })
public class SaveServlet extends HttpServlet {
private String url, user, pass; // written once in init, then read-only
@Override
public void init() {
url = getInitParameter("dbUrl");
user = getInitParameter("dbUser");
pass = System.getenv("DB_PASSWORD"); // never hard-code secrets
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String sql = "INSERT INTO applicant(name, scheme_id) VALUES (?, ?)";
try (Connection con = DriverManager.getConnection(url, user, pass);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, req.getParameter("name")); // parameters are numbered from 1
ps.setInt(2, Integer.parseInt(req.getParameter("scheme")));
ps.executeUpdate(); // INSERT/UPDATE/DELETE → int row count
} catch (SQLException e) {
throw new ServletException(e);
}
resp.sendRedirect("thanks.jsp"); // post-redirect-get
}
}PreparedStatement takes the SQL once with ? placeholders and fills them by position (the first is 1, not 0); it is faster when repeated and keeps user input apart from the SQL text, which is why it is preferred over building queries by string concatenation. executeQuery() returns a ResultSet (read with while (rs.next())), while executeUpdate() returns the number of rows changed. In production, containers supply a pooled DataSource through JNDI rather than DriverManager.
| JDBC driver | Name | How it talks to the database |
|---|---|---|
| Type 1 | JDBC-ODBC bridge | Translates JDBC calls into ODBC calls (class sun.jdbc.odbc.JdbcOdbcDriver); removed from Java in version 8 |
| Type 2 | Native-API driver | Calls the vendor's native client library (for example Oracle OCI); needs that library on the client |
| Type 3 | Network-protocol / middleware driver | Sends calls to a middleware server that talks to the database; pure Java on the client |
| Type 4 | Thin / native-protocol driver | Pure Java; speaks the database's own network protocol directly; the usual choice today |
Class.forName("driver.class.Name") is no longer required. Creating the driver object or calling Class.forName ran its static block, which registered it with DriverManager — the idea older papers test.Scriptlets mix Java into HTML and quickly become unreadable. Modern JSP avoids them. The Expression Language (EL) reads data with ${…}: ${user.name} calls getName() on the bean found under user. EL looks for the name in page, request, session and application scope, in that order, and prints nothing (rather than failing) when it is missing. It also offers implicit objects such as param (request parameters: ${param.district}), header, cookie, sessionScope and requestScope, plus operators (==, &&, empty, +).
The JSP Standard Tag Library (JSTL) supplies tags for logic and output. The core library is declared with a taglib directive and the prefix c. Use c:out to print values, because it escapes special characters by default — one neutral habit that keeps user-supplied text from being interpreted as markup.
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- Jakarta Tags 3.0 (Jakarta EE 10) also accepts uri="jakarta.tags.core"; the old URI still works --%>
<c:if test="${empty schemes}"><p>No schemes found.</p></c:if>
<ul>
<c:forEach var="s" items="${schemes}">
<li><c:out value="${s}" /></li>
</c:forEach>
</ul>
<p>Logged in as <c:out value="${sessionScope.user}" default="guest" /></p>| Core tag | Does |
|---|---|
c:out | Prints a value, escaping markup characters |
c:set / c:remove | Sets / removes a variable in a scope |
c:if | Conditional (no else) |
c:choose / c:when / c:otherwise | If–else-if chain / switch |
c:forEach | Loops over a collection or a numeric range |
c:redirect, c:url, c:import | Redirect, build URLs (with session id), include another resource |
Good structure matters as much as syntax. Early JSP projects ("Model 1") let each JSP receive the request, run the SQL and show the result — quick to write, hard to maintain. Model 2, the MVC (Model–View–Controller) pattern, splits the work: a servlet is the controller (receives the request, validates, calls business code, picks the view), JavaBeans or other classes are the model (data and business logic, including database access), and JSP pages are the view (presentation only, using EL and JSTL). The controller stores the model in request scope and forwards to the JSP, as in SchemeListServlet earlier. Struts and Spring MVC are frameworks built on this idea.
Two more container features are asked about. A filter (jakarta.servlet.Filter, with init, doFilter(request, response, chain) and destroy) sits in front of servlets and JSPs: it can log, authenticate, compress or change requests and responses, then call chain.doFilter to pass control onward. A listener is told about events: ServletContextListener (application start/stop), HttpSessionListener (session created/destroyed), ServletRequestListener, and attribute listeners.
@WebFilter("/*")
public class TimingFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
long start = System.nanoTime();
chain.doFilter(req, res); // run the servlet or JSP
long ms = (System.nanoTime() - start) / 1_000_000;
((HttpServletRequest) req).getServletContext().log("request took " + ms + " ms");
}
}| Servlet | JSP | PHP | ASP.NET | |
|---|---|---|---|---|
| Language | Java | Java in HTML, plus tags | PHP | C# or VB.NET |
| Runs in | Servlet container (Tomcat) | Same container, via generated servlet | PHP engine (Apache module or FastCGI) | .NET runtime on IIS or Kestrel |
| Execution | Compiled bytecode, one instance, many threads | Translated and compiled once, then as a servlet | Interpreted per request (opcode cache helps) | Compiled to assembly, thread per request |
| Best at | Control logic, processing forms | Presentation, templates | Quick web pages | Event-driven forms with controls |
| Session object | HttpSession | session | $_SESSION | Session["key"] |
| Typical extension | .java / .class | .jsp | .php | .aspx |
Try the problem first, then reveal the working one step at a time.
A page hits.jsp is requested 3 times. The developer then edits the file. It is requested 2 more times and the server is then shut down. How many times do translation, compilation, jspInit, _jspService and jspDestroy run in total?
/apply.html posts to /apply. The servlet does req.setAttribute("msg", "Saved"); req.getRequestDispatcher("/result.jsp").forward(req, resp); and result.jsp contains <p>${msg}</p>. A second variant replaces the last call with resp.sendRedirect("result.jsp"). Trace both: what URL appears, how many requests are made and what is printed?
web.xml sets <session-timeout>30</session-timeout>. A user's requests arrive at minutes 0, 10, 35 and 70 (relative to the first). At which requests is a new session created, and when would the session have expired if the user had stopped after minute 35?
Predict the three outputs when this page is requested three times in a row (same container, page not edited in between): <%! int a = 0; %> <% int b = 0; a++; b++; %> a=<%= a %> b=<%= b %>
main.jsp contains <%@ include file="menu.jspf" %> and later <%= x %>. The file menu.jspf contains <% int x = 5; %>. Does it compile? What happens if the directive is replaced by <jsp:include page="menu.jsp" /> (same content saved as menu.jsp)?
Choose the best scope (page, request, session or application) for each item and say why: (a) a user's shopping cart, (b) a hit counter for the whole site, (c) the list of search results a controller hands to a view for one display, (d) a loop counter used only inside one JSP.
A web.xml declares servlets A (load-on-startup 2), B (load-on-startup 1), C (no element) and D (load-on-startup 0). In which order does the container create them, and when is C created?
Write the order of JDBC steps and the methods used to insert a row (name, age) into table applicant safely, and state what executeUpdate returns.
forward and sendRedirect are opposites in four ways: forward is server-side, one request, URL unchanged, attributes kept; redirect is browser-side, two requests, URL changes, attributes lost. The redirect method belongs to response, never to request.<%! %> create fields shared by all requests, whereas scriptlet variables are local to one request. The generated _jspService can never be overridden, but jspInit and jspDestroy can.jsp:include works at request time as a separate servlet. Papers often ask for the translation-time one.web.xml session-timeout is in minutes, setMaxInactiveInterval in seconds. The 30-minute default is a container setting (Tomcat), not a specification rule; other containers or older books may state different defaults, so read the question for a stated value.javax.servlet, while Jakarta EE 9+ (and the specifications) use jakarta.servlet; some textbooks list isThreadSafe (default true) as a normal page attribute although Pages 3.1 deprecates it (removal planned for 4.0) because SingleThreadModel is gone from Servlet 6.0; some say a JSP is compiled "at every request", which is wrong — only the first request after a change pays for it.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.