Unit 4: JavaServer Pages
I. JSP Fundamentals
JavaServer Pages (JSP) is a server-side Java technology used to create dynamic web content. A JSP page combines static markup such as HTML with JSP elements, Expression Language, and Java-based server components. The web container translates each JSP into a servlet, compiles it, and executes it to produce an HTTP response.
- Governing principle: JSP separates presentation from request-processing and business logic; servlets or controllers process requests, while JSP pages render views.
- Execution environment: A JSP requires a servlet container such as Apache Tomcat, Eclipse Jetty, or another Jakarta EE-compatible server.
- Server-side execution: JSP code runs on the server; the browser receives only generated content such as HTML, JSON, or XML.
- Translation model: A page such as
profile.jspis translated into a Java servlet class before requests are served. - File convention: JSP source files normally use the
.jspextension; JSP documents written in XML syntax commonly use.jspx. - Modern practice: Expression Language, JSTL, JavaBeans, and MVC controllers are preferred over embedding substantial Java code in JSP pages.
- API naming:
- Modern Jakarta EE uses packages beginning with
jakarta.servlet.jsp. - Older Java EE applications use packages beginning with
javax.servlet.jsp.
- Modern Jakarta EE uses packages beginning with
II. JSP Page Processing — Container-Managed Execution
A. Lifecycle of a JSP page
The lifecycle of a JSP page is the sequence through which the container translates, initializes, executes, and eventually destroys the generated servlet.
- Translation: The container converts the JSP source into servlet source code, usually when the page is requested for the first time or when its source changes.
- Static HTML becomes output statements.
- JSP elements become corresponding Java statements or methods.
- Translation errors occur when JSP syntax or directives are invalid.
- Compilation: The generated servlet source is compiled into Java bytecode.
- A Java syntax error inside a scriptlet may cause compilation to fail.
- Containers commonly cache the compiled class for later requests.
- Class loading: The servlet container loads the generated class using its class loader.
- Instantiation: The container creates an instance of the generated servlet class.
- Initialization: The container invokes
jspInit()once after creating the JSP servlet.- It is used for initialization that belongs to the JSP instance.
- It corresponds to the servlet lifecycle’s
init()phase.
- Request processing: For every request, the container invokes
_jspService(request, response).- It generates the response using static markup, expressions, actions, and page data.
- The container generates this method; JSP authors must not declare or override it.
- Concurrent requests may execute this method on the same JSP servlet instance, so unsafe shared mutable fields should be avoided.
- Destruction: Before removing the page instance, the container calls
jspDestroy()once.- It can release resources owned by the instance.
- It corresponds to the servlet lifecycle’s
destroy()phase.
public void jspInit() {
// One-time initialization
}
public void jspDestroy() {
// Resource cleanup
}- Lifecycle order: The normal sequence is translation, compilation, class loading, instantiation,
jspInit(), repeated_jspService()calls, andjspDestroy(). - Modification handling: If the JSP file changes, the container normally retranslates and recompiles it before serving the updated version.
III. JSP Application Organization — Deployment Layout
A. Directory structure of JSP
A JSP application follows the standard Java web-application directory structure so that the container can distinguish public resources from protected configuration and Java components.
MyWebApp/
├── index.jsp
├── images/
│ └── logo.png
├── css/
│ └── style.css
├── WEB-INF/
│ ├── web.xml
│ ├── views/
│ │ └── account.jsp
│ ├── classes/
│ │ └── com/example/Account.class
│ └── lib/
│ └── utility.jar
└── META-INF/
└── MANIFEST.MF- Document root: The top-level directory contains resources that clients may request directly, such as
index.jsp, CSS files, JavaScript, and images. WEB-INFdirectory: Resources underWEB-INFcannot be requested directly through a browser URL.- Controllers can forward requests to JSP views stored in
WEB-INF/views. - This prevents users from bypassing controller logic.
- Controllers can forward requests to JSP views stored in
web.xml: The deployment descriptor may define servlets, filters, listeners, welcome files, error pages, and security constraints.WEB-INF/classes: Contains compiled application classes arranged according to their Java package structure.WEB-INF/lib: Contains JAR dependencies required by the application, such as tag libraries or database drivers.META-INF: Holds archive-level metadata, particularly when the application is packaged as a Web Application Archive.- WAR packaging: The directory can be packaged as
MyWebApp.warand deployed to a servlet container. - View placement: A public
index.jspis directly addressable, whereas/WEB-INF/views/account.jspmust be reached through server-side forwarding.
IV. JSP Programming Interface — Core Types and Services
A. JSP API
The JSP API defines interfaces and classes used by generated JSP servlets, containers, page contexts, writers, and custom tag libraries.
JspPage: The base JSP lifecycle interface, extending the servlet contract withjspInit()andjspDestroy().HttpJspPage: ExtendsJspPagefor HTTP-based JSP pages and defines_jspService().PageContext: Provides access to page attributes, request data, response data, session state, application state, and request dispatching.JspWriter: A buffered writer used to send generated output to the client; it is exposed through the implicit objectout.JspFactory: Supplies implementation-dependent JSP objects, especiallyPageContextinstances, to generated servlet code.JspException: Represents general errors raised during JSP or tag processing.SkipPageException: Signals that processing of the remaining JSP page should stop.- Tag extension API: The
jakarta.servlet.jsp.tagextpackage supports custom tags through types such asTag,SimpleTag, andTagSupport. - Container responsibility: Application code normally does not instantiate API implementation classes; the JSP container creates and coordinates them.
- Portability: Programming against standard JSP interfaces allows pages and tag handlers to operate across compatible containers.
V. Embedded Java Statements — Request-Time Logic
A. Scriptlet tag
A scriptlet tag inserts Java statements into the generated _jspService() method and therefore executes for each request.
<%
String user = request.getParameter("user");
if (user == null) {
user = "Guest";
}
%>
<p>Welcome, <%= user %></p>- Syntax: A scriptlet begins with
<%and ends with%>. - Permitted content: It can contain assignments, method calls, loops, conditionals, and local variable declarations.
- Object access: Scriptlets can directly use implicit objects such as
request,session, andout. - Execution scope: Variables declared in a scriptlet are normally local to
_jspService()and exist only during that request. - Output: Content may be written explicitly with
out.println(...), although expression tags are shorter for simple values. - Limitation: Mixing Java statements with HTML reduces readability, complicates testing, and weakens separation of concerns.
- Preferred approach: Controllers, Expression Language, JSTL tags, and JavaBeans should handle logic in modern JSP applications.
VI. Dynamic Value Output — Expression Evaluation
A. Expression tag
An expression tag evaluates a Java expression during request processing and writes its resulting value directly to the response.
<p>Current user: <%= request.getParameter("user") %></p>
<p>Total: <%= 10 * 5 %></p>- Syntax: An expression begins with
<%=and ends with%>. - Generated operation:
<%= value %>is conceptually translated toout.print(value). - Semicolon rule: The expression itself must not end with a semicolon because it is supplied as an argument to an output method.
- Valid content: Method calls, arithmetic expressions, variables, property access, and conditional expressions may be used.
- Return requirement: The enclosed code must evaluate to a value; declarations and control-flow statements are not valid expressions.
- Conversion: Primitive and object values are converted to textual form by the output mechanism.
- Escaping limitation: Expression tags do not automatically guarantee HTML escaping, so untrusted request data can create cross-site scripting risks.
- Modern equivalent: Expression Language is usually clearer, as in
${param.user}.
VII. Class-Level Members — Shared JSP Definitions
A. Declaration tag
A declaration tag adds fields or methods to the generated servlet class rather than placing code inside _jspService().
<%!
private String formatName(String name) {
return name == null ? "Guest" : name.trim();
}
%>
<p><%= formatName(request.getParameter("name")) %></p>- Syntax: A declaration begins with
<%!and ends with%>. - Generated location: Its content appears at class level in the translated servlet.
- Typical content: It may define fields, constants, helper methods, or initialization-related members.
- Lifetime: Instance fields may survive across multiple requests because they belong to the JSP servlet instance.
- Concurrency risk: Multiple request threads can access the same instance field simultaneously, causing races or data leakage.
- Local comparison:
- A declaration creates a class-level member.
- A scriptlet declaration creates a request-local variable inside
_jspService().
- Design limitation: Business methods and mutable application state belong in Java classes or managed components, not JSP declarations.
VIII. Built-In Page Variables — Container-Provided Context
A. JSP implicit objects
JSP implicit objects are predefined variables made available by the container without explicit declaration.
request: TheHttpServletRequestcontaining parameters, headers, cookies, attributes, and request details.response: TheHttpServletResponseused to set status codes, headers, content type, or redirects.out: TheJspWriterthat writes buffered page output.session: The currentHttpSession, used for user-specific state across requests; it is unavailable when the page directive setssession="false".application: TheServletContext, shared across the entire web application.config: TheServletConfigassociated with the generated JSP servlet.pageContext: ThePageContextthat coordinates attributes, scopes, writers, forwarding, and inclusion.page: A reference to the generated servlet instance, comparable to Java’sthis.exception: TheThrowableassociated with an error page; it is available only when the page is declared withisErrorPage="true".- Attribute scopes:
- Page scope lasts for the current JSP execution.
- Request scope lasts for one request, including forwards.
- Session scope lasts across requests in one user session.
- Application scope lasts while the web application remains active.
<%
request.setAttribute("message", "Account created");
session.setAttribute("username", "Asha");
application.setAttribute("siteName", "Student Portal");
%>IX. Standard JSP Operations — XML-Style Action Elements
A. JSP action tags
JSP action tags perform standard runtime operations such as bean handling, resource inclusion, forwarding, and parameter transfer.
<jsp:useBean>: Locates an existing JavaBean or creates one in a specified scope.
<jsp:useBean id="student"
class="com.example.Student"
scope="request" /><jsp:setProperty>: Assigns a value to a JavaBean property.
<jsp:setProperty name="student" property="name" value="Meera" /><jsp:getProperty>: Reads a bean property and writes it to the response.
<jsp:getProperty name="student" property="name" /><jsp:include>: Includes another resource’s output at request time.
<jsp:include page="/header.jsp" />- Dynamic inclusion: Because the target executes for each request, its current output is inserted into the response.
<jsp:forward>: Transfers request processing to another server-side resource and normally ends processing of the current page.
<jsp:forward page="/WEB-INF/views/login.jsp" /><jsp:param>: Adds a request parameter to aninclude,forward, or plugin action.
<jsp:include page="/result.jsp">
<jsp:param name="mode" value="compact" />
</jsp:include><jsp:plugin>: Generates browser-specific markup for a Java plugin or applet; it is obsolete for modern web applications.- Action timing: Unlike directives, action tags are evaluated while the request is being processed.
- Syntax requirement: Actions use XML-style syntax, must be properly closed, and belong to the reserved
jspnamespace.
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 →