Unit 4: JavaServer Pages - Subjective Questions
CSE406 — Advanced Java Programming • Practice Questions with Detailed Answers
20 questions
Define JavaServer Pages (JSP). Explain its role in developing Java web applications.
JavaServer Pages (JSP) is a server-side technology used to create dynamic web pages by embedding Java-related elements into HTML or other text-based documents.
Role of JSP:
- JSP is mainly used as the presentation layer of a Java web application.
- It enables dynamic content to be inserted into otherwise static HTML pages.
- A JSP page is translated into a servlet and executed by the web container.
- It can access JavaBeans, request parameters, session data, databases through Java classes, and other server-side resources.
- In the MVC architecture, JSP commonly acts as the View, while servlets act as controllers and Java classes implement business logic.
JSP simplifies page development because developers can write HTML directly instead of generating every HTML element through servlet output statements.
Describe the complete lifecycle of a JSP page.
The lifecycle of a JSP page is managed by the JSP container and consists of the following phases:
- Translation: The container translates the JSP page into an equivalent servlet source file.
- Compilation: The generated servlet source is compiled into a Java class.
- Class loading: The container loads the compiled servlet class into memory.
- Instantiation: An instance of the generated servlet class is created.
- Initialization: The container invokes
jspInit()once to initialize the JSP servlet. - Request processing: For every client request, the container invokes
_jspService(request, response). This method generates the response. - Destruction: Before removing the JSP servlet, the container invokes
jspDestroy()once so that resources can be released.
Translation and compilation usually occur when the JSP is requested for the first time or after the JSP file has been modified.
Explain the lifecycle methods jspInit(), _jspService(), and jspDestroy(). State whether a JSP author can override each method.
jspInit()
- It is called exactly once after the generated JSP servlet is instantiated.
- It is used to initialize resources such as configuration data or helper objects.
- A JSP author may define or override this method using a declaration.
_jspService()
- It is called once for every request received by the JSP page.
- It receives
HttpServletRequestandHttpServletResponseobjects. - It contains the translated output and processing logic of the JSP page.
- A JSP author must not define or override it because the container generates this method from the JSP content.
jspDestroy()
- It is called once before the generated servlet is removed from service.
- It is used to close files, database connections, or other long-lived resources.
- A JSP author may define or override this method using a declaration.
Therefore, jspInit() and jspDestroy() can be customized, but _jspService() is controlled by the JSP container.
Describe the standard directory structure of a JSP-based web application.
A JSP web application normally follows the standard Java web application directory structure:
- Application root: Contains publicly accessible resources such as JSP files, HTML files, CSS files, JavaScript files, and images.
WEB-INF/: Contains protected application resources that cannot be requested directly by a browser.WEB-INF/web.xml: The optional deployment descriptor containing servlet mappings, welcome pages, filters, listeners, session settings, and other configuration.WEB-INF/classes/: Contains compiled application classes arranged according to their Java package structure.WEB-INF/lib/: Contains JAR libraries required by the application.META-INF/: May contain metadata such asMANIFEST.MFand container-specific configuration.
A typical structure is:
app/
index.jspcss/style.cssimages/WEB-INF/web.xmlWEB-INF/classes/com/example/MyClass.classWEB-INF/lib/library.jar
Files under WEB-INF are protected from direct client access but remain available to server-side components.
What is the JSP API? Explain its major packages, interfaces, and classes.
The JSP API provides the interfaces and classes required by a web container to translate, execute, and manage JSP pages. In modern Jakarta applications, these types are under jakarta.servlet.jsp; older Java EE applications use javax.servlet.jsp.
Important API elements include:
JspPage: Extends the servlet lifecycle withjspInit()andjspDestroy().HttpJspPage: Represents an HTTP-specific JSP page and defines_jspService().JspWriter: A buffered writer used by JSP pages to send content to the client.PageContext: Provides access to page attributes, scoped data, implicit objects, and request forwarding or inclusion facilities.JspFactory: Creates and releasesPageContextobjects and provides container-specific JSP support.JspException: Represents errors raised during JSP or tag processing.JspEngineInfo: Supplies information about the JSP engine version.
The related tag extension package, jakarta.servlet.jsp.tagext or the older javax.servlet.jsp.tagext, supports the implementation of custom JSP tags.
Define a JSP scriptlet tag. Explain its syntax, execution, and limitations with an example.
A scriptlet tag contains Java statements that are inserted into the generated servlet's _jspService() method.
Syntax: <% Java statements; %>
Example:
<%
String user = request.getParameter("user");
if (user != null) {
out.println("Welcome, " + user);
}
%>
Execution:
- The code runs whenever the JSP processes a request.
- It can access implicit objects such as
request,response,session, andout. - Local variables declared in a scriptlet belong to
_jspService()and are generally request-specific.
Limitations:
- It mixes Java logic with presentation markup.
- It makes pages difficult to test and maintain.
- Complex scriptlets can violate MVC separation.
- Modern JSP development favors Expression Language, JSTL, JavaBeans, and controller servlets instead of scriptlets.
What is a JSP expression tag? Explain how it differs from a scriptlet that calls out.print().
A JSP expression tag evaluates an expression and writes its value directly to the response.
Syntax: <%= expression %>
Example: <p>Current user: <%= request.getParameter("name") %></p>
It is translated into code similar to an out.print() call inside _jspService().
Difference from a scriptlet:
- Expression syntax is
<%= value %>, while scriptlet syntax is<% statements %>. - An expression produces a value that is automatically written to the output.
- A scriptlet must explicitly use
out.print()orout.println()to generate output. - An expression does not normally end with a semicolon because it is an expression rather than a complete Java statement.
For example, <%= total %> is approximately equivalent to <% out.print(total); %>.
Explain the JSP declaration tag. How does a variable declared in a declaration differ from one declared in a scriptlet?
A JSP declaration tag declares fields or methods at the class level of the generated servlet.
Syntax: <%! declaration %>
Example:
<%!
private int requestCount = 0;
public String formatName(String name) {
return name == null ? "Guest" : name.toUpperCase();
}
%>
Declaration variable:
- Becomes an instance field of the generated servlet.
- Can exist across multiple requests.
- May be accessed concurrently by several request-processing threads.
- Requires synchronization or another thread-safe design when it is mutable.
Scriptlet variable:
- Becomes a local variable inside
_jspService(). - Is created separately for each request invocation.
- Is normally not shared between concurrent requests.
Declarations should not be used for request-specific mutable state because a JSP servlet instance may serve multiple users simultaneously.
Compare JSP scriptlet, expression, and declaration tags with respect to syntax, generated location, and purpose.
The three JSP scripting elements have different purposes:
| Element | Syntax | Generated location | Purpose |
|---|---|---|---|
| Scriptlet | <% statements %> |
Inside _jspService() |
Executes Java statements for each request |
| Expression | <%= expression %> |
Inside _jspService() as output code |
Evaluates and writes a value to the response |
| Declaration | <%! fields or methods %> |
At class level in the generated servlet | Declares servlet fields and methods |
Examples:
- Scriptlet:
<% int total = 10 + 20; %> - Expression:
<%= total %> - Declaration:
<%! private String appName = "Portal"; %>
Scriptlet variables are local to request processing, whereas declaration fields may be shared by concurrent requests. Expression tags automatically send their result to out. In modern applications, Expression Language, JSTL, and Java classes are generally preferred over all three scripting elements.
What are JSP implicit objects? List the standard implicit objects and state their purposes.
JSP implicit objects are predefined variables created by the JSP container and made available to a JSP page without explicit declaration.
The standard implicit objects are:
request: Contains the client's request data, parameters, headers, and request attributes.response: Represents the HTTP response sent to the client.out: AJspWriterused to write page content.session: Represents the user'sHttpSession, when session support is enabled.application: Represents the sharedServletContextof the web application.config: Provides the generated servlet's configuration throughServletConfig.pageContext: Provides access to all JSP scopes, implicit objects, and page-related operations.page: Refers to the current generated servlet instance and is similar tothis.exception: Represents an uncaughtThrowable; it is available only on a JSP error page configured withisErrorPage="true".
These objects reduce boilerplate code and provide direct access to common web application services.
Explain the request, response, and out implicit objects, including one typical use of each.
request object:
- Usually implements
HttpServletRequest. - Contains request parameters, attributes, cookies, headers, and client information.
- Example:
request.getParameter("email")retrieves a submitted form value.
response object:
- Usually implements
HttpServletResponse. - Controls the response status, headers, content type, cookies, and redirection.
- Example:
response.sendRedirect("login.jsp")redirects the client.
out object:
- Is an instance of
JspWriter. - Writes text and markup into the JSP response buffer.
- Example:
out.println("<p>Welcome</p>")writes HTML output.
Although out can be used directly, placing static HTML in the JSP and using Expression Language for dynamic values generally produces clearer presentation code.
Distinguish between the page, pageContext, config, and application implicit objects.
page: Refers to the current JSP servlet instance. It is equivalent to usingthisin the generated servlet and should rarely be required in a JSP page.pageContext: Represents the JSP execution environment. It can retrieve and store attributes in page, request, session, and application scopes. It also provides access to other implicit objects and supports forwarding and inclusion.config: RepresentsServletConfigfor the generated JSP servlet. It provides servlet initialization parameters and access to theServletContext.application: Represents theServletContextshared by the entire web application. It is used for application-wide attributes, resources, logging, and context information.
The key difference is scope and responsibility: page identifies the servlet instance, pageContext manages page execution and scopes, config stores component configuration, and application represents shared web application state.
Explain JSP attribute scopes and describe how pageContext can be used to manage scoped attributes.
JSP supports four attribute scopes:
- Page scope: Available only within the current JSP page while it processes the request.
- Request scope: Available to components processing the same request, including forwarded or included resources.
- Session scope: Available across multiple requests from the same user session.
- Application scope: Available to all users and components in the web application.
pageContext can manage all four scopes using methods such as:
pageContext.setAttribute("key", value, PageContext.REQUEST_SCOPE)pageContext.getAttribute("key", PageContext.REQUEST_SCOPE)pageContext.removeAttribute("key", PageContext.REQUEST_SCOPE)pageContext.findAttribute("key")
findAttribute() searches in the order page, request, session, application and returns the first matching attribute. Data should be stored in the narrowest scope that satisfies its required lifetime to reduce unintended sharing and memory usage.
Explain the session and exception implicit objects. Under what conditions can each object be used?
session implicit object:
- Represents the current user's
HttpSession. - It stores user-specific information across multiple requests, such as a login identity or shopping cart.
- It is available by default.
- If a JSP page uses the page directive
session="false", thesessionimplicit object is unavailable on that page.
exception implicit object:
- Refers to the uncaught
Throwablethat caused control to be transferred to an error page. - It is available only when the page directive includes
isErrorPage="true". - It can be used to display a controlled error message or to log diagnostic information.
For example, a normal JSP may specify errorPage="error.jsp", while error.jsp specifies isErrorPage="true" and can then access exception.getMessage().
What are JSP action tags? Explain their general syntax and how they differ from JSP scripting elements.
JSP action tags are XML-style elements that request standard operations from the JSP container at request-processing time.
General syntax:
- With a body:
<jsp:action attribute="value">body</jsp:action> - Without a body:
<jsp:action attribute="value" />
Common standard actions include:
<jsp:include><jsp:forward><jsp:param><jsp:useBean><jsp:setProperty><jsp:getProperty><jsp:element>,<jsp:attribute>, and<jsp:body>
Difference from scripting elements:
- Action tags use XML-like syntax, whereas scripting elements embed Java code.
- Actions represent container-supported behavior and are generally easier to read.
- Actions are processed during request handling.
- Scriptlets, expressions, and declarations are translated into Java code in the generated servlet.
Action tags support cleaner JSP pages and reduce the amount of embedded Java code.
Describe the <jsp:include> action. Compare it with the JSP include directive.
The <jsp:include> action dynamically includes the output of another resource while the request is being processed.
Example:
<jsp:include page="header.jsp">
<jsp:param name="title" value="Dashboard" />
</jsp:include>
Action versus directive:
| Feature | <jsp:include> action |
<%@ include %> directive |
|---|---|---|
| Time | Request-processing time | Translation time |
| Included content | Generated output of the target resource | Source text of the target file |
| Update behavior | Target changes are normally visible independently | Parent JSP may require retranslation |
| Parameters | Can pass parameters using <jsp:param> |
Does not use <jsp:param> |
| Best use | Dynamic JSP, servlet, or resource output | Static reusable fragments |
The action includes the target resource's response output, whereas the directive merges file contents into the JSP before compilation.
Explain the <jsp:forward> and <jsp:param> action tags with an example. How is forwarding different from redirection?
<jsp:forward> transfers the current request and response to another server-side resource. <jsp:param> adds a request parameter for the target resource.
Example:
<jsp:forward page="result.jsp">
<jsp:param name="status" value="success" />
</jsp:forward>
The target can retrieve the parameter using request.getParameter("status").
Forwarding:
- Occurs internally on the server.
- Reuses the same request and response objects.
- Does not normally change the URL displayed in the browser.
- Can pass request attributes and action parameters.
- Must occur before the response has been committed.
Redirection:
- Sends a redirect response to the browser.
- Causes the browser to issue a new request.
- Changes the browser URL.
- Does not automatically preserve request attributes.
Execution of the forwarding JSP does not continue normally after a successful <jsp:forward> action.
Explain the <jsp:useBean> action and the significance of its id, class, type, and scope attributes.
The <jsp:useBean> action locates an existing JavaBean in a specified scope or creates one when an appropriate bean is not found.
Example: <jsp:useBean id="student" class="com.example.Student" scope="session" />
Attributes:
id: Specifies the name used to reference the bean and the scoped attribute name.class: Specifies the concrete class to instantiate when the bean does not already exist. The class normally requires an accessible no-argument constructor.type: Specifies the reference type expected for the bean. It may be an interface or superclass. If onlytypeis supplied, a missing bean cannot generally be instantiated.scope: Determines where the bean is stored. Valid values arepage,request,session, andapplication; the default ispage.
The body of <jsp:useBean> is executed only when the action creates a new bean, allowing initial property values to be assigned.
Describe the <jsp:setProperty> and <jsp:getProperty> action tags. Explain the meaning of property="*".
<jsp:setProperty> assigns a value to a JavaBean property by calling the corresponding setter method.
Examples:
<jsp:setProperty name="student" property="name" value="Anita" /><jsp:setProperty name="student" property="age" param="studentAge" />
<jsp:getProperty> retrieves a bean property by calling its getter and writes the result to the response.
Example: <jsp:getProperty name="student" property="name" />
The name attribute must match the id used by <jsp:useBean>.
When <jsp:setProperty name="student" property="*" /> is used, the container attempts to match request parameter names with writable bean property names. For example, a request parameter named email may be assigned through setEmail(...). Automatic conversion is available for common simple types, but validation and secure field selection are still necessary. Explicitly selecting accepted properties is preferable when mass assignment could modify sensitive data.
Develop and explain a JSP-based flow that receives user data, stores it in a JavaBean, and displays it on another page using JSP action tags.
A two-page flow can use a request-scoped JavaBean.
Processing page:
<jsp:useBean id="user" class="com.example.UserBean" scope="request" />
<jsp:setProperty name="user" property="name" param="name" />
<jsp:setProperty name="user" property="email" param="email" />
<jsp:forward page="display.jsp" />
Display page:
<jsp:useBean id="user" type="com.example.UserBean" scope="request" />
<p>Name: <jsp:getProperty name="user" property="name" /></p>
<p>Email: <jsp:getProperty name="user" property="email" /></p>
Explanation:
<jsp:useBean>creates the bean and places it in request scope.<jsp:setProperty>copies selected request parameters into bean properties.<jsp:forward>transfers the same request todisplay.jsp.- The second page locates the existing request-scoped bean.
<jsp:getProperty>reads and displays its properties.
In production code, input should be validated in a servlet or service layer, output should be escaped to prevent cross-site scripting, and JSP should remain focused on presentation.
Define JavaServer Pages (JSP). Explain its role in developing Java web applications.
JavaServer Pages (JSP) is a server-side technology used to create dynamic web pages by embedding Java-related elements into HTML or other text-based documents.
Role of JSP:
- JSP is mainly used as the presentation layer of a Java web application.
- It enables dynamic content to be inserted into otherwise static HTML pages.
- A JSP page is translated into a servlet and executed by the web container.
- It can access JavaBeans, request parameters, session data, databases through Java classes, and other server-side resources.
- In the MVC architecture, JSP commonly acts as the View, while servlets act as controllers and Java classes implement business logic.
JSP simplifies page development because developers can write HTML directly instead of generating every HTML element through servlet output statements.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →