First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.
Continue in the practice tool above to load more questions, 50 at a time.
Question 1Java EE 7 Platform and Web Application Architecture
A Java EE 7 web application must be packaged so the container can discover annotated servlets, filters, and listeners without any deployment descriptor. Which artifact is required at the root of the archive?
- A META-INF/persistence.xml file
- A web.xml file declaring metadata-complete="true"
- A WEB-INF/classes directory containing the compiled classes
- An empty WEB-INF/web.xml file or a web.xml with metadata-complete set to false Correct answer.
Explanation
Annotation scanning for web components is enabled when the archive contains a web.xml whose metadata-complete attribute is false or absent, and an empty web.xml is the canonical way to trigger scanning. If no web.xml exists at all, the container may still scan, but the portable and reliable approach is an empty descriptor. Setting metadata-complete to true disables annotation processing entirely.
Question 2Java EE 7 Platform and Web Application Architecture
An application needs a component that runs once at startup, initializes a shared cache, and is guaranteed to be invoked before any request is served. Which Java EE 7 web component fits best?
- A filter mapped to /* with async-supported enabled
- A stateless session bean with a @PostConstruct method
- A ServletContextListener registered with @WebListener Correct answer.
- A servlet mapped to /* with load-on-startup 1
Explanation
A ServletContextListener receives contextInitialized before the web application begins serving requests, making it the standard place for one-time startup initialization. The other options either run per request or depend on lazy activation timing that is not guaranteed to precede all requests.
Question 3Java EE 7 Platform and Web Application Architecture
Which statement correctly describes the relationship between a web module and an EJB module inside the same EAR file?
- The web module can inject EJBs from the EJB module using @EJB because both share the same class loader hierarchy within the EAR. Correct answer.
- Each module in an EAR is isolated and EJBs cannot be referenced from web modules at all.
- The EJB module must be packaged inside WEB-INF/lib to be visible to the web module.
- The web module must look up EJBs through JNDI only, since injection is not supported across modules.
Explanation
Within an EAR, modules are loaded by a shared parent class loader, and the container supports @EJB injection of beans declared in sibling EJB modules. JNDI lookup remains possible but is not the only mechanism. Packaging the EJB JAR inside WEB-INF/lib is unnecessary and non-standard for cross-module references.
Question 4Java EE 7 Platform and Web Application Architecture
A developer wants a servlet to process requests asynchronously so a slow backend call does not hold a container thread. Which combination is required in Java EE 7?
- Configure the connector with executor="async" and call request.startAsync() from a filter.
- Declare async-supported="true" on the servlet and its filters, then call startAsync() on the request. Correct answer.
- Annotate the servlet with @Asynchronous and return a Future from doGet.
- Enable async-supported only on the servlet; filters never need the flag.
Explanation
Servlet 3.0+ asynchronous processing requires the servlet and every filter in the chain to declare async-supported true, after which the request can be put into async mode with startAsync(). The @Asynchronous annotation belongs to EJB, not servlets. Omitting the flag on any filter in the chain causes an IllegalStateException.
Question 5Java EE 7 Platform and Web Application Architecture
Which annotation declares a RESTful web service class in a Java EE 7 application, and what is the default scope of such a class?
- @Singleton on the class, with application scope by default
- @WebService on the class, with session scope by default
- @Path on the class, with a per-request lifecycle by default Correct answer.
- @Stateless on the class, with singleton scope by default
Explanation
JAX-RS resource classes are identified by @Path, and by default a new resource instance is created for each request. Combining @Path with an EJB annotation such as @Stateless changes the lifecycle, but the default for a plain JAX-RS class is per-request. @WebService is for JAX-WS endpoints, not REST resources.
Question 6Java EE 7 Platform and Web Application Architecture
A JAX-RS resource method returns a Response object. Which statement about @Produces on that method is accurate?
- @Produces is ignored when the method returns Response; the Content-Type must be set manually.
- @Produces determines the media type used for content negotiation and is applied to the entity written from the Response. Correct answer.
- @Produces must be declared on the class and cannot appear on individual methods.
- @Produces on the method applies only if the client sends an Accept header.
Explanation
@Produces declares the media types a resource method can produce and participates in content negotiation with the client's Accept header. It may be declared at class or method level, with method-level declarations overriding class-level ones. Returning Response does not disable the annotation.
Question 7Java EE 7 Platform and Web Application Architecture
Which CDI annotation combination makes a bean eligible for injection into a JAX-RS resource in a Java EE 7 container?
- @Stateless with @LocalBean
- @ManagedBean with @RequestScoped
- A bean class with a bean-defining annotation such as @Dependent or a scope annotation, discovered via beans.xml or implicit discovery Correct answer.
- @Named with @SessionScoped
Explanation
CDI treats a class as a managed bean when it carries a bean-defining annotation such as a scope or @Dependent, and the archive is a bean archive. In Java EE 7 with implicit bean discovery, archives containing bean-defining annotations are bean archives even without beans.xml. @ManagedBean is the older JSF annotation and does not make a CDI bean.
Question 8Java EE 7 Platform and Web Application Architecture
Which scope should be chosen for a CDI bean that holds conversational state spanning multiple requests until the user explicitly ends the conversation?
- @RequestScoped
- @ApplicationScoped
- @Dependent
- @ConversationScoped Correct answer.
Explanation
@ConversationScoped maintains state across multiple requests and is bounded by Conversation.begin() and Conversation.end(), which is exactly the multi-request conversational pattern. @RequestScoped lives for a single request, @ApplicationScoped is shared across all users, and @Dependent follows the lifecycle of its injection point.
Question 9Java EE 7 Platform and Web Application Architecture
A servlet needs to read a configuration value defined in web.xml as a context parameter. Which API retrieves it?
- request.getParameter("name") on the HttpServletRequest
- getServletContext().getInitParameter("name") Correct answer.
- getServletConfig().getInitParameter("name")
- getServletContext().getAttribute("name")
Explanation
Context parameters declared with <context-param> are read through ServletContext.getInitParameter. Servlet init parameters are read through ServletConfig.getInitParameter, and request parameters come from the query string or form body. Attributes are objects set at runtime, not declarative configuration values.
Question 10Java EE 7 Platform and Web Application Architecture
What is the primary purpose of the WEB-INF directory in a Java EE web application archive?
- To hold static resources that are served directly to browsers
- To store classes, libraries, and configuration that are not directly accessible via URL Correct answer.
- To hold deployment descriptors for EJB modules
- To contain the application client module for the EAR
Explanation
WEB-INF is a protected area holding web.xml, compiled classes, and JAR libraries; the container prevents clients from requesting its contents directly. Static resources intended for direct access belong outside WEB-INF. Application client and EJB descriptors live in their own modules.
Question 11Java EE 7 Platform and Web Application Architecture
A JAX-RS application needs to apply a logging concern to every resource method without modifying each method. Which mechanism is appropriate?
- A ContainerRequestFilter and ContainerResponseFilter registered with the application Correct answer.
- A servlet filter mapped to the JAX-RS servlet path only
- An EJB interceptor bound with @Interceptors on each resource class
- A @PostConstruct method in each resource class
Explanation
JAX-RS filters intercept requests and responses at the JAX-RS layer and can be registered application-wide, giving cross-cutting behavior for all resource methods. Servlet filters operate at the HTTP layer and are less aware of JAX-RS semantics. Interceptors must be bound per class or via a binding annotation, and @PostConstruct runs only at instance creation.
Question 12Java EE 7 Platform and Web Application Architecture
Which statement about JNDI lookup of a stateless session bean from a servlet in the same application is correct?
- The portable form java:module/BeanName or java:app/BeanName can be used when the bean is in the same application. Correct answer.
- JNDI lookup is impossible for EJBs and only injection works.
- The lookup string must reference the physical JAR file name.
- The lookup string must always be the fully qualified global JNDI name beginning with java:global.
Explanation
Java EE defines portable JNDI namespaces: java:module for components in the same module, java:app for the same application, and java:global for a fully qualified name. Using java:app or java:module avoids hard-coding container-specific global names. The global name is valid but not required.
Question 13Java EE 7 Platform and Web Application Architecture
A developer wants a JSF backing bean to be CDI-managed, accessible from Facelets expressions, and retain state across postbacks to the same view. Which annotation set is correct in Java EE 7?
- @Stateless and @Named together
- @ManagedBean and @ViewScoped from javax.faces.bean
- @Named and a CDI scope such as @ViewScoped from javax.faces.view Correct answer.
- @Named and @ManagedBean together
Explanation
In Java EE 7, use @Named for EL resolution with javax.faces.view.ViewScoped to retain CDI-managed state across postbacks to the same view. This scope annotation is CDI-aware, unlike javax.faces.bean.ViewScoped, which belongs to the legacy JSF managed bean facility.
Question 14Java EE 7 Platform and Web Application Architecture
Which element of web.xml defines the URL pattern for a servlet?
- <context-param> containing <param-name>
- <servlet> containing <url-pattern>
- <servlet-mapping> containing <servlet-name> and <url-pattern> Correct answer.
- <filter-mapping> containing <servlet-name>
Explanation
Servlet URL patterns are declared in <servlet-mapping>, which pairs a <servlet-name> with one or more <url-pattern> entries. The <servlet> element declares the servlet class and init parameters but not its URL. Filter mappings and context parameters serve different purposes.
Question 15Java EE 7 Platform and Web Application Architecture
What does the metadata-complete attribute on the web-app element control?
- Whether the container scans annotations and web fragments in the module Correct answer.
- Whether the servlet container enables asynchronous processing
- Whether the container validates the descriptor against the schema
- Whether the application is deployed in a clustered environment
Explanation
When metadata-complete is true, the container skips annotation scanning and ignores web-fragment descriptors, relying solely on web.xml. Setting it to false or omitting it enables scanning. It does not affect schema validation, clustering, or async support.
Question 16Java EE 7 Platform and Web Application Architecture
An application uses @EJB to inject a stateful session bean into a servlet field. Which statement about this injection is correct?
- The stateful bean is shared by all clients of the application.
- The injected reference is a distinct stateful bean instance per HTTP request.
- Injection of stateful session beans into servlets is prohibited.
- The injected reference is a proxy that resolves to a stateful bean instance associated with the client, typically the calling session. Correct answer.
Explanation
The container injects a client proxy for the stateful session bean, and each client, typically identified by the session, gets its own bean instance behind that proxy. Stateful beans are never shared across clients by design. Injection into servlets is allowed and the proxy preserves per-client state.
Question 17Java EE 7 Platform and Web Application Architecture
Which file declares a JPA persistence unit for a Java EE application?
- WEB-INF/web.xml
- META-INF/beans.xml
- META-INF/application.xml
- META-INF/persistence.xml in the EJB module or WEB-INF/classes/META-INF/persistence.xml in the web module Correct answer.
Explanation
A persistence unit is declared in persistence.xml, located in META-INF of an EJB module or in WEB-INF/classes/META-INF of a web module. web.xml configures web components, application.xml describes EAR modules, and beans.xml enables CDI.
Question 18Java EE 7 Platform and Web Application Architecture
A REST resource class is annotated with @Path("/orders") and contains a method annotated with @GET and @Path("{id}"). What does the method parameter annotated with @PathParam("id") receive?
- The entity body deserialized from the request
- The value of the path segment matched by the {id} template Correct answer.
- The value of the HTTP header named id
- The query parameter named id from the request URL
Explanation
@PathParam binds a method parameter to the URI template variable declared in @Path, so the value of the segment matched by {id} is injected. Query parameters use @QueryParam, headers use @HeaderParam, and the body is bound without an annotation or with an entity parameter.
Question 19Java EE 7 Platform and Web Application Architecture
Which statement best describes the role of the Java EE 7 Full Platform profile compared with the Web Profile?
- The Web Profile includes EJB Lite and JAX-RS but excludes technologies such as JMS and the full EJB component model. Correct answer.
- The Web Profile is a superset of the Full Platform.
- The Full Platform excludes JAX-RS and JSF.
- The Web Profile excludes CDI and JPA.
Explanation
The Web Profile is a subset of the Full Platform that includes web technologies, CDI, JPA, EJB Lite, and JAX-RS, but omits full EJB features, JMS, and other enterprise APIs. The Full Platform adds those technologies. The Web Profile does include CDI and JPA, and the Full Platform includes JAX-RS and JSF.
Question 20Java EE 7 Platform and Web Application Architecture
A filter must wrap the request so downstream components see modified header values. Which method of the Filter interface performs this wrapping?
- init, by storing the wrapped request in the FilterConfig
- destroy, by releasing the wrapped request
- doFilter, by passing a wrapped ServletRequest to the FilterChain Correct answer.
- service, by overriding the servlet's request handling
Explanation
A filter's doFilter method receives the request, response, and chain, and can pass a wrapped request to chain.doFilter so downstream components see the modified view. init and destroy handle filter lifecycle, and service belongs to the Servlet interface, not Filter.
Question 21Servlets and JavaServer Pages (JSP)
In a Java EE 7 web application, which interface must a class implement to be registered as a filter through the @WebFilter annotation?
- javax.servlet.Filter Correct answer.
- javax.servlet.http.HttpServlet
- javax.servlet.ServletRequestListener
- javax.servlet.ServletContainerInitializer
Explanation
The @WebFilter annotation marks a class that implements javax.servlet.Filter, and the container invokes its doFilter method for matching requests. The annotation is only recognized on a Filter implementation, so the type of the class determines whether the annotation has effect.
Question 22Servlets and JavaServer Pages (JSP)
A servlet needs to read a request parameter named 'page' that may be absent. Which method returns null when the parameter is not present?
- request.getParameter("page") Correct answer.
- request.getHeader("page")
- request.getParameterValues("page")
- request.getAttribute("page")
Explanation
getParameter returns the first value of the named request parameter, or null if the parameter does not exist. getAttribute reads request-scoped attributes, which are a different mechanism from parameters.
Question 23Servlets and JavaServer Pages (JSP)
Which JSP directive is used to declare that a page uses UTF-8 encoding and imports java.util.List?
- <%@ page %> Correct answer.
- <%@ taglib %>
- <%@ tag %>
- <%@ include %>
Explanation
The page directive carries attributes such as pageEncoding, contentType, and import, so it is the correct place for encoding and import declarations. The include directive statically includes another resource, and taglib declares tag libraries.
Question 24Servlets and JavaServer Pages (JSP)
A developer wants a servlet to be initialized with a startup parameter before any request arrives. Which annotation element accomplishes this?
- @WebServlet(asyncSupported = true)
- @WebServlet(urlPatterns = "/init")
- @WebServlet(name = "init")
- @WebServlet(loadOnStartup = 1) Correct answer.
Explanation
The loadOnStartup element causes the container to instantiate and initialize the servlet eagerly at startup, and its init method can read init parameters. A positive value indicates startup ordering rather than waiting for the first request.
Question 25Servlets and JavaServer Pages (JSP)
Which implicit JSP object provides access to request parameters and attributes within a scriptlet?
- pageContext
- request Correct answer.
- application
- session
Explanation
The implicit object request is the HttpServletRequest for the current request, exposing parameters and request attributes. The other implicit objects represent different scopes or the page context.
Question 26Servlets and JavaServer Pages (JSP)
What is the default session timeout behavior when no timeout is configured in web.xml or via setMaxInactiveInterval?
- The session expires after 30 minutes of inactivity. Correct answer.
- The session never expires.
- The session expires when the browser closes.
- The session expires after 60 minutes of inactivity.
Explanation
The Servlet specification defines a default session timeout of 30 minutes of inactivity when no explicit configuration exists. The timeout is measured from the last request associated with the session, not from creation.
Question 27Servlets and JavaServer Pages (JSP)
Which method of HttpServletResponse should be called before writing binary content to the response output stream?
- addCookie
- sendRedirect
- setContentType Correct answer.
- encodeURL
Explanation
setContentType must be called before the response is committed so the container can send the correct Content-Type header for binary data. Once the output stream is flushed and the response committed, headers can no longer be changed.
Question 28Servlets and JavaServer Pages (JSP)
A JSP page uses an EL expression ${sessionScope.cart.total}. What does the sessionScope identifier refer to?
- A request parameter named sessionScope
- A cookie collection
- A map of session attributes Correct answer.
- The HttpSession object itself
Explanation
sessionScope is an implicit EL object that maps session attribute names to their values, so ${sessionScope.cart} retrieves the session attribute named cart. It is a map-like view, not the HttpSession instance.
Question 29Servlets and JavaServer Pages (JSP)
A servlet must forward a request to /WEB-INF/views/report.jsp while preserving request attributes. Which code achieves this?
- response.sendRedirect("/WEB-INF/views/report.jsp")
- request.getRequestDispatcher("/WEB-INF/views/report.jsp").forward(request, response) Correct answer.
- response.sendError(302, "/WEB-INF/views/report.jsp")
- request.getRequestDispatcher("/WEB-INF/views/report.jsp").include(request, response)
Explanation
A RequestDispatcher forward transfers control server-side, so request attributes remain visible to the target JSP. Resources under WEB-INF are not directly addressable by clients, which makes forwarding the only workable option among these.
Question 30Servlets and JavaServer Pages (JSP)
Which annotation declares a servlet that handles only HTTP GET requests at /status?
- @WebServlet(value = "/status", method = "GET")
- @WebServlet(name = "/status")
- @WebServlet(urlPatterns = "/status") with a doGet method Correct answer.
- @WebServlet(urlPatterns = "/status") with a service method only
Explanation
@WebServlet maps the URL pattern, and the container dispatches GET requests to the servlet's doGet method through HttpServlet. There is no method element on @WebServlet for restricting HTTP verbs.
Question 31Servlets and JavaServer Pages (JSP)
A filter must run only for requests whose URL starts with /admin. Which @WebFilter element is appropriate?
- servletNames = "admin"
- dispatcherTypes = DispatcherType.REQUEST
- urlPatterns = "/admin/*" Correct answer.
- filterName = "adminFilter"
Explanation
The urlPatterns element accepts servlet URL patterns, and /admin/* matches any path beginning with /admin. The filter is then applied by the container only to matching request URLs.
Question 32Servlets and JavaServer Pages (JSP)
A JSP page needs to display the same header on many pages without duplicating markup. Which directive performs a translation-time inclusion of header.jspf?
- <jsp:forward page="header.jspf" />
- <jsp:include page="header.jspf" />
- <%@ include file="header.jspf" %> Correct answer.
- <%@ taglib prefix="h" uri="header" %>
Explanation
The include directive is processed at translation time, so the included file's content becomes part of the generated servlet. This differs from the jsp:include action, which includes the response at request time.
Question 33Servlets and JavaServer Pages (JSP)
Which statement about the lifecycle of a servlet is correct?
- init is called once per request before service.
- The container creates a new servlet instance for each request by default.
- destroy is called after every request completes.
- A single servlet instance typically handles concurrent requests, so instance fields are shared. Correct answer.
Explanation
The container normally creates one servlet instance and invokes service on it from multiple threads, so mutable instance fields must be synchronized or avoided. init runs once after construction, and destroy runs once when the servlet is taken out of service.
Question 34Servlets and JavaServer Pages (JSP)
A servlet sets a request attribute and then calls RequestDispatcher.forward. Which statement describes the response state?
- The forward automatically commits the response before the target runs.
- The forward discards any request attributes set before the call.
- The target resource can write to the response, and the original servlet must not write afterward. Correct answer.
- Both the original servlet and the target can write to the response independently.
Explanation
Forward transfers responsibility for the response to the target resource; the calling servlet should not write after forwarding. Request attributes set before the forward remain available to the target.
Question 35Servlets and JavaServer Pages (JSP)
How can a servlet mark a session as invalid so that subsequent requests receive a new session?
- session.invalidate() Correct answer.
- session.setMaxInactiveInterval(0)
- session.removeAttribute("id")
- response.addCookie(new Cookie("JSESSIONID", ""))
Explanation
invalidate discards the session and unbinds its attributes, so a later request that needs a session causes the container to create a new one. Setting the timeout to zero or clearing attributes does not destroy the session object.
Question 36Servlets and JavaServer Pages (JSP)
A JSP page must avoid scriptlets and use a custom tag to format currency. Which pair of declarations enables the tag?
- An include directive, plus a jsp:forward action
- A taglib directive with a prefix and uri, plus a TLD that defines the tag Correct answer.
- A page directive with import, plus a scriptlet
- A page directive with session=false, plus EL
Explanation
Custom tags are declared with the taglib directive, which binds a prefix to a URI resolved through a tag library descriptor. The TLD defines the tag handler class and attributes that the container uses at translation time.
Question 37Servlets and JavaServer Pages (JSP)
Which EL expression safely handles a null nested property when displaying a user's address city?
- ${not empty user.address ? user.address.city : ''} Correct answer.
- ${user.address.city}
- ${user!.address!.city}
- ${user.address.city} with no null checks
Explanation
EL evaluates property access on null as null rather than throwing, but a conditional with the empty operator lets the page render a fallback value explicitly. The ternary form avoids rendering a literal null string in the output.
Question 38Servlets and JavaServer Pages (JSP)
A servlet writes a large file to the response. Which pair of settings is most appropriate?
- setStatus(204) and flushBuffer
- sendRedirect and addCookie
- setContentType with the file MIME type and setContentLength with the file size Correct answer.
- setCharacterEncoding and getWriter
Explanation
Declaring the MIME type tells the client how to interpret the bytes, and setting the content length allows the client to show progress and detect truncation. Binary output should go through getOutputStream rather than getWriter.
Question 39Servlets and JavaServer Pages (JSP)
Which listener interface should be implemented to react when an HttpSession is created and destroyed?
- ServletRequestListener
- ServletContextListener
- HttpSessionListener Correct answer.
- HttpSessionAttributeListener
Explanation
HttpSessionListener provides sessionCreated and sessionDestroyed callbacks for the session lifecycle. The context and request listeners respond to application and request events instead.
Question 40Servlets and JavaServer Pages (JSP)
A JSP uses <jsp:useBean id="cart" class="shop.Cart" scope="session" />. What happens if no session attribute named cart exists?
- The container creates a Cart instance and stores it in the session scope. Correct answer.
- The container throws an InstantiationException at translation time.
- The container forwards the request to an error page.
- The container creates a new Cart for every subsequent request.
Explanation
jsp:useBean looks up the named attribute in the specified scope and, when absent, instantiates the class with its no-argument constructor and stores it there. Subsequent requests reuse the stored session attribute.
Question 41Servlets and JavaServer Pages (JSP)
A web application must share a database connection pool across all servlets. Which scope and mechanism are appropriate?
- Store the pool as a ServletContext attribute initialized in a ServletContextListener. Correct answer.
- Store the pool as a session attribute created per user.
- Store the pool as a servlet instance field in each servlet.
- Store the pool as a request attribute set by each servlet.
Explanation
ServletContext attributes are shared across the whole application, and a ServletContextListener provides a place to create the pool at startup and close it at shutdown. Per-servlet or per-user storage would duplicate or leak resources.
Question 42Servlets and JavaServer Pages (JSP)
A filter wraps the request to compress the response body. Which wrapper class is the correct base for intercepting output written by downstream servlets?
- ServletOutputStream subclass alone
- HttpServletRequestWrapper
- HttpServletResponseWrapper Correct answer.
- ServletRequestEvent
Explanation
HttpServletResponseWrapper delegates to the original response and can override getOutputStream or getWriter to capture and transform output. The request wrapper is for request-side interception, not response body handling.
Question 43Servlets and JavaServer Pages (JSP)
An asynchronous servlet calls asyncContext.start with a Runnable that writes the response. Which statement is required for correctness?
- The servlet must be declared with asyncSupported=true and must call complete when finished. Correct answer.
- The servlet must disable session tracking before starting the Runnable.
- The servlet must call response.sendRedirect before starting the Runnable.
- The servlet must be mapped with urlPatterns ending in /*.
Explanation
Asynchronous processing requires asyncSupported on the servlet and its filters, and the application must eventually call complete on the AsyncContext to finish the response. The container keeps the response open until completion.
Question 44Servlets and JavaServer Pages (JSP)
A JSP page is included with <jsp:include page="frag.jsp" />. Which statement about request attributes set before the include is correct?
- They are visible only if the include uses the include directive instead.
- They are visible in frag.jsp because the include shares the same request. Correct answer.
- They are discarded because jsp:include creates a new request.
- They are visible only if frag.jsp declares session=false.
Explanation
jsp:include runs the target as a separate resource but passes the same request and response objects, so request attributes remain visible. The runtime include differs from a forward mainly in that the original page continues processing.
Question 45Servlets and JavaServer Pages (JSP)
A servlet needs to send a 404 status with a custom HTML body. Which approach is correct?
- response.sendRedirect("/404.html")
- response.sendError(404) then write the HTML body
- throw new ServletException("404")
- response.setStatus(404) then write the HTML to getWriter Correct answer.
Explanation
setStatus records the status code without committing the response, so the servlet can still write a custom body. sendError delegates error page handling to the container and commits the response.
Question 46Servlets and JavaServer Pages (JSP)
A servlet needs to read a request parameter named 'page' that may appear multiple times in the query string. Which HttpServletRequest method returns all submitted values for that parameter?
- getParameterMap().get("page")
- getParameterValues("page") Correct answer.
- getParameterNames()
- getParameter("page")
Explanation
getParameterValues returns a String array containing every value submitted under the given name, which is exactly what is needed when a parameter can repeat. getParameter collapses repeated values to the first one, so it loses data. The map and enumeration methods give access to names or single values, not the full value list for one name.
Question 47Servlets and JavaServer Pages (JSP)
A JSP page must import java.util.List and set the response content type to text/html with UTF-8 encoding using directives only. Which pair of directives accomplishes this?
- <%@ page import="java.util.List" %> and <%@ page contentType="text/html; charset=UTF-8" %> Correct answer.
- <%@ include file="list.jsp" %> and <%@ page session="true" %>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> and <%@ page isELIgnored="false" %>
- <%@ page errorPage="error.jsp" %> and <%@ page buffer="8kb" %>
Explanation
The page directive's import attribute adds types to the generated servlet's imports, and its contentType attribute sets the response MIME type and character encoding. Both are translation-time directives, so they satisfy the requirement without scriptlets. Other page attributes control error handling, buffering, or session participation, and taglib/include do not set the response type.
Question 48Servlets and JavaServer Pages (JSP)
A servlet container must be told that a servlet supports concurrent requests so that a long-running request can release the container thread. Which pair of steps is required to use asynchronous processing in a servlet declared with @WebServlet?
- Set asyncSupported=true on the annotation and call request.startAsync() to obtain an AsyncContext Correct answer.
- Annotate the servlet with @WebListener and override requestInitialized
- Call request.getRequestDispatcher().forward() and then request.startAsync()
- Implement SingleThreadModel and call response.flushBuffer() before processing
Explanation
Asynchronous support must be declared with asyncSupported=true on the servlet (and on any filters in the chain), and the servlet then invokes startAsync on the request to receive an AsyncContext. The AsyncContext lets the servlet complete the response later from another thread. Forwarding does not start async mode, and SingleThreadModel restricts concurrency instead of enabling it.
Question 49Servlets and JavaServer Pages (JSP)
A servlet wants to store an object so that it is available to every servlet in the web application and survives for the life of the application, while remaining safe under concurrent access. Which combination is appropriate?
- Call getServletContext().setAttribute with a thread-safe object, since context attributes are shared application-wide Correct answer.
- Call getSession().setAttribute with the object, since sessions are shared between users
- Call request.setAttribute with the object, since request attributes are visible to all servlets
- Call getServletConfig().getServletContext().getInitParameter to publish the object to all servlets
Explanation
ServletContext attributes are shared by all servlets and components in the same web application and live as long as the application, so they are the right scope for application-wide shared state. Because many threads may access them concurrently, the stored object must itself be thread-safe or externally synchronized. Request and session scopes are per-request or per-user, and init parameters are read-only Strings.
Question 50Servlets and JavaServer Pages (JSP)
A JSP page uses JSTL to iterate over a collection and must display the loop status, such as whether the current item is the first one, without using a scriptlet. Which approach provides the index and first/last flags inside <c:forEach>?
- Reference the implicit object ${pageContext.loopStatus} inside the loop body
- Declare the loop variable with the varStatus attribute and read properties such as ${status.first} from the resulting LoopTagStatus Correct answer.
- Declare the loop variable with the var attribute and read ${item.index} from the current element
- Call ${fn:length(items)} on each iteration to compare the current position with the collection size
Explanation
The varStatus attribute of <c:forEach> exports a LoopTagStatus object whose properties include index, count, first, and last, so the loop position can be inspected in EL. The var attribute only exports the current element itself. pageContext does not expose a loop status object, and computing lengths per iteration does not give reliable first/last flags.