Compilation and Runtime Lifecycle
When a JSP file is first requested, the servlet container (e.g., Tomcat) translates it into a Java class that extends HttpJspBase, which itself inherits from HttpServlet. This generated class is then compiled into bytecode and loaded into memory. Subsequent requests bypass translation and directly invoke the compiled servlet.
The lifecycle includes two custom methods:
public void _jspInit() { }
public void _jspDestroy() { }
These are invoked during initialization and cleanup, respectively, separate from the standard init() and destroy() methods of HttpServlet.
The generated Java source reveals how JSP content is transformed into out.write() calls. For example, static HTML is output as string literals, while embedded Java code (scriptlets) is inserted verbatim into the _jspService() method.
JSP Directives
JSP directives control page-level behavior and are declared using <%@ ... %>. Three primary directives exist:
- page: Configures the JSP page’s environment.
- include: Embeds static content at translation time.
- taglib: Declares custom tag libraries for reuse.
Key attributes of the page directive:
import: Imports Java packages (e.g.,import="java.util.*").contentType: Defines MIME type and character encoding (e.g.,text/html; charset=UTF-8).pageEncoding: Specifies the encoding of the JSP file itself.session: Enables/disables HTTP session access (default: true).errorPage: Redirects to a designated error page on uncaught exceptions.isErrorPage: Marks the current page as an error handler, exposing theexceptionimplicit object.isELIgnored: Disables Expression Language evaluation (default: false).
Example: Error handling with errorPage and isErrorPage:
<%@ page errorPage="/error.jsp" %>
<% int x = 1 / 0; %>
<%@ page isErrorPage="true" %>
<h1>Error Occurred: ${exception.message}</h1>
Include Directives vs. Action Tags
Two mechanisms exist for including content:
- Directive include (
<%@ include file="..." %>): Static inclusion at translation time. The included file’s source is merged into the main JSP before compilation. Results in a single servlet. - Action include (
<jsp:include page="..." flush="true" />): Dynamic inclusion at request time. Each included file is compiled separately, and its output is inserted during execution. Supports parameter passing.
Example with dynamic inclusion and parameters:
<jsp:include page="/header.jsp" flush="true">
<jsp:param name="title" value="Home Page" />
</jsp:include>
JavaBeans and Standard Actions
JSP supports interaction with JavaBeans through standardized actions:
- jsp:useBean: Locates or creates a JavaBean instance.
- jsp:setProperty: Sets bean properties from request parameters or literals.
- jsp:getProperty: Retrieves and outputs a bean property.
Example: Handling form submission with a User bean:
<jsp:useBean id="user" class="com.example.User" scope="page" />
<jsp:setProperty name="user" property="*" />
Name: <jsp:getProperty name="user" property="name" /><br>
Age: <jsp:getProperty name="user" property="age" /><br>
The property="*" syntax automatically maps request parameters to matching bean seters.
Scopes determine visibility:
page: Available only in the current JSP.request: Available during the current HTTP request.session: Available across multiple requests from the same user.application: Shared across all users of the web application.
Example: Session vs. Application counters:
<jsp:useBean id="userCounter" class="Counter" scope="session" />
<jsp:useBean id="totalCounter" class="Counter" scope="application" />
Your visits: <jsp:getProperty name="userCounter" property="count" /><br>
Total visits: <jsp:getProperty name="totalCounter" property="count" />
Forward Action
The <jsp:forward> action transfers control to another resource, effectively replacing the current response:
<jsp:forward page="/dashboard.jsp">
<jsp:param name="userId" value="123" />
</jsp:forward>
This is equivalent to RequestDispatcher.forward() in servlets and does not return to the original page.
Implicit Objects
JSP provides nine built-in objects accessible without declaration:
| Object | Type | Description |
|---|---|---|
| out | JspWriter | Output stream for writing content to the response. |
| request | ServletRequest | Represents the HTTP request. |
| responce | ServletResponse | Represents the HTTP response. |
| config | ServletConfig | Provides access to servlet initialization parameters. |
| session | HttpSession | Stores user-specific data across requests. |
| application | ServletContext | Shared context for the entire web application. |
| page | Object | Reference to the current servlet instance (equivalent to this). |
| pageContext | PageContext | Encapsulates access to all other implicit objects and page-level features. |
| exception | Exception | Available only in error pages; holds the thrown exception. |
Expression Language (EL)
EL simplifies data access using a concise syntax: ${expression}. It eliminates the need for scriptlets to retrieve attributes or bean properties.
EL accesses data through implicit objects:
${pageScope.name}— retrieves from page scope${requestScope.name}— from request scope${sessionScope.name}— from session scope${applicationScope.name}— from application scope${param.name}— retrieves a single request parameter${paramValues.name[0]}— retrieves the first value from multi-value parameters${header["User-Agent"]}— accesses HTTP headers${cookie.JSESSIONID.value}— reads cookie values${initParam.appName}— reads context parameters fromweb.xml
EL also supports bean property access:
${user.name}
${user.age}
It automatically handles null values and type coercion, making templates cleaner and safer than scriptlets.
Configuration
JSPs can be configured via web.xml using <jsp-file> instead of <servlet-class>:
<servlet>
<servlet-name>MyJspPage</servlet-name>
<jsp-file>/pages/index.jsp</jsp-file>
</servlet>
This allows URL mapping to JSP files, similar to servlets.