Unit 4: JavaServer Pages

CSE406 — Advanced Java Programming 9 min read

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.jsp is translated into a Java servlet class before requests are served.
  • File convention: JSP source files normally use the .jsp extension; 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.

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.
JAVA
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, and jspDestroy().
  • 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.

TEXT
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-INF directory: Resources under WEB-INF cannot 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.
  • 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.war and deployed to a servlet container.
  • View placement: A public index.jsp is directly addressable, whereas /WEB-INF/views/account.jsp must 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 with jspInit() and jspDestroy().
  • HttpJspPage: Extends JspPage for 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 object out.
  • JspFactory: Supplies implementation-dependent JSP objects, especially PageContext instances, 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.tagext package supports custom tags through types such as Tag, SimpleTag, and TagSupport.
  • 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.

JSP
<%
    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, and out.
  • 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.

JSP
<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 to out.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().

JSP
<%!
    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:
    1. A declaration creates a class-level member.
    2. 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: The HttpServletRequest containing parameters, headers, cookies, attributes, and request details.
  • response: The HttpServletResponse used to set status codes, headers, content type, or redirects.
  • out: The JspWriter that writes buffered page output.
  • session: The current HttpSession, used for user-specific state across requests; it is unavailable when the page directive sets session="false".
  • application: The ServletContext, shared across the entire web application.
  • config: The ServletConfig associated with the generated JSP servlet.
  • pageContext: The PageContext that coordinates attributes, scopes, writers, forwarding, and inclusion.
  • page: A reference to the generated servlet instance, comparable to Java’s this.
  • exception: The Throwable associated with an error page; it is available only when the page is declared with isErrorPage="true".
  • Attribute scopes:
    1. Page scope lasts for the current JSP execution.
    2. Request scope lasts for one request, including forwards.
    3. Session scope lasts across requests in one user session.
    4. Application scope lasts while the web application remains active.
JSP
<%
    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
<jsp:useBean id="student"
             class="com.example.Student"
             scope="request" />
  • <jsp:setProperty>: Assigns a value to a JavaBean property.
JSP
<jsp:setProperty name="student" property="name" value="Meera" />
  • <jsp:getProperty>: Reads a bean property and writes it to the response.
JSP
<jsp:getProperty name="student" property="name" />
  • <jsp:include>: Includes another resource’s output at request time.
JSP
<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
<jsp:forward page="/WEB-INF/views/login.jsp" />
  • <jsp:param>: Adds a request parameter to an include, forward, or plugin action.
JSP
<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 jsp namespace.