JSP Scopes and Anatomy
JSP Scopes and Anatomy
JSP defines four standard scopes in which you can store and retrieve objects. They determine the
lifecycle and visibility of attributes you set.
A typical JSP mixes static template text (HTML/XML) with dynamic Java code and standard actions. Its
elements include:
1. Directives
Control overall JSP settings (translation phase)
3. Scriptlets
Inline Java code inserted into the `_jspService()` method
5. Comments
JSP comment (not sent to client): `<%-- This won’t appear in HTML --%>`
6. Standard Actions
8. Template Text
Any static content (HTML, CSS, JavaScript) outside of JSP tags is copied verbatim to the
response.
jsp
<html>
<head><title>JSP Anatomy Demo</title></head>
<body>
<%-- Scriptlet: increment counter --%>
<%
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/17
visitCount++;
// Put counter in session scope
session.setAttribute("visits", visitCount);
%>
<h1>Welcome!</h1>
<p>Current time: <%= new Date() %></p>
<p>You have visited this page <strong>${sessionScope.visits}</strong> times this session.</p>
1. Translation
4. Request Processing
5. Cleanup
When the container decides to unload the JSP (e.g., application shutdown or redeploy), it calls
`jspDestroy()`—for cleanup.
Flow Diagram
pgsql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/17
Key Takeaways
Uploaded image
same
Implicit
Java Type JSP Scope Description
Object
Note: there are other implicit objects too (e.g. `out`, `config`, `page`, `response`, `exception`),
but the four above correspond directly to the four JSP attribute scopes.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/17
1. `<jsp:useBean>`
2. `<jsp:setProperty>`
3. `<jsp:getProperty>`
2.2. Example
java
`// src/com/example/User.java
package com.example;
public User() { }
jsp
<html>
<head><title>Bean Demo</title></head>
<body>
<h2>Bean Properties:</h2>
<ul>
<li>Name: <jsp:getProperty name="user" property="name" /></li>
<li>Age: <jsp:getProperty name="user" property="age" /></li>
</ul>
</body>
</html>
`
`<jsp:useBean>`
`<jsp:setProperty>`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/17
Sets one or more bean properties
`<jsp:getProperty>`
Parameter passing ❌ cannot pass request parameters ✅ can pass `<jsp:param>` sub-
elements
Reflects changes in
Requires re-translation/restart Immediately sees any changes
included file
Overhead Very low (no extra HTTP dispatch) Slightly higher (dispatch + buffer flush)
Dynamic fragments (changing menus,
Typical use case Stable templates (headers, footers)
ads)
JavaBeans in JSP
Use the three tags—`<jsp:useBean>`, `<jsp:setProperty>`, `<jsp:getProperty>`—to instantiate, set,
and get bean properties.
Includes
Choose the directive for static, compile‐time merging; choose the action tag for dynamic, runtime
inclusion (with parameters, and immediate picks up changes).
Develop and deploy a simple filter that forwards only those requcsts that come ftom the host
having the IP address "172.16.4.248"
Below is a complete example of a servlet Filter that only allows requests originating from the IP address
`172.16.4.248` to proceed to your application; all other requests get forwarded to an error page. We’ll
show:
3. A simple `error.jsp`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/17
4. Steps to package and deploy on Apache Tomcat
`package com.example.filters;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// no init params needed
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String remoteIp = request.getRemoteAddr();
if (ALLOWED_IP.equals(remoteIp)) {
// IP matches – continue down the chain (to servlets, JSPs, etc.)
chain.doFilter(request, response);
} else {
// IP does not match – forward to an error page
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
req.getRequestDispatcher("/error.jsp")
.forward(req, resp);
}
}
@Override
public void destroy() {
// nothing to clean up
}
}
`
xml
`<filter>
<filter-name>IPAllowFilter</filter-name>
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/17
<filter-class>com.example.filters.IPAllowFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>IPAllowFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
`
Make sure your filter class no longer has `@WebFilter`, or disable servlet-annotation scanning.
3. The `error.jsp`
Place this in `webapps/yourapp/error.jsp`:
jsp
Make sure your project follows the standard Maven/Gradle layout (or plain `WEB-INF/classes`,
`WEB-INF/lib`).
Summary
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/17
Package as a WAR and drop into Tomcat’s `webapps` to deploy.
Below are the answers to (i) and (iii); as requested, we’re skipping the filter question.
java
or any JSP page that uses the implicit `session` object (which under the covers invokes
`request.getSession()`).
Cookie mode (default): container sends a `Set-Cookie: JSESSIONID=…` header when the
session is created.
URL mode (if cookies disabled): container rewrites URLs to include `;jsessionid=…` so the
client can circulate the ID.
Lifecycle point.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/17
Tip: You can control session creation on JSP pages via the page directive:
jsp
which disables the implicit `session` object and prevents auto-creation of `JSESSIONID`.
Custom tags let you encapsulate reusable presentation logic in tag libraries. Here’s a simple end-to-end
example.
java
`// src/com/example/tags/HelloTag.java
package com.example.tags;
import java.io.IOException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.JspWriter;
@Override
public void doTag() throws IOException {
JspWriter out = getJspContext().getOut();
out.print("Hello, " + name + "!");
}
}
`
Create `/WEB-INF/tlds/mytags.tld`:
xml
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/17
<tlib-version>1.0</tlib-version>
<short-name>MyTags</short-name>
<uri>http://example.com/mytags</uri>
<tag>
<name>hello</name>
<tag-class>com.example.tags.HelloTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
`
jsp
<br/>
The `<%@ taglib %>` directive binds the `mt` prefix to your TLD’s URI.
4. Deployment Notes
3. Ensure your web.xml (or container) scans and picks up TLDs in `WEB-INF/tlds`.
4. Deploy as a WAR (or exploded directory) to your servlet container—Tomcat, Jetty, etc.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/17
jsp
`Hello, Jane!
`
Summary
`JSESSIONID` is issued on the very first `HttpSession` creation (via `request.getSession()` or implicit
JSP session).
Custom tags require a Java handler (often extending `SimpleTagSupport`), a TLD entry, and a JSP
taglib directive to use.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/17
jsp
<html>
<head><title>Demo: errorPage</title></head>
<body>
<%
// Simulate an uncaught exception:
if (true) {
throw new RuntimeException("Oops—something went wrong!");
}
%>
<p>This line will never execute.</p>
</body>
</html>
`
jsp
<html>
<head><title>Error Occurred</title></head>
<body>
<h1>Sorry—an error happened!</h1>
<p><strong>Exception:</strong> <%= exception.getClass().getName() %></p>
<p><strong>Message:</strong> <%= exception.getMessage() %></p>
<hr/>
<p><em>We’ll log this and try to fix it ASAP.</em></p>
</body>
</html>
`
`isErrorPage="true"` allows this JSP to see the implicit `Throwable exception` object.
The container automatically forwards here whenever the “main” JSP throws an uncaught exception.
jsp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/17
java
`package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
try {
// Scriptlet: out.println(msg);
out.println(msg);
// Expression: <%= msg %> → out.print(msg);
out.print(msg);
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out.clear();
pageContext.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(pageContext);
}
}
Breakdown
`<%! … %>` → becomes a field (`private String msg…`) in the servlet class.
`<% out.println(msg); %>` → in `_jspService` you see `out.println(msg);`.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/17
how to make jsp page thread safe ?
By default, each JSP is compiled into a servlet and a single servlet instance services all requests
concurrently on multiple threads. That means any instance fields or shared resources you introduce in
your JSP (via `<%! … %>`, or by storing non‐thread-safe objects in application/session scope) can be
accessed by multiple requests at once—and lead to race conditions.
jsp
Under the covers this makes your JSP servlet implement the (now-deprecated)
`javax.servlet.SingleThreadModel` interface. The container guarantees only one thread at a time will
execute your JSP—at the cost of throughput (it may pool multiple servlet instances or serialize all
requests).
Drawbacks
All your per-request state should live in local variables inside scriptlets or (better) in your backing
beans/servlets.
jsp
`<%
// THREAD-SAFE: msg is a local variable
String msg = "Hello, JSP!";
out.println(msg);
%>
`
`<%!
// shared across all threads → NOT thread-safe!
private int counter = 0;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/17
%>
`
jsp
`<%
AtomicInteger visits =
(AtomicInteger) session.getAttribute("visits");
if (visits == null) {
visits = new AtomicInteger(0);
session.setAttribute("visits", visits);
}
out.println("Visits: " + visits.incrementAndGet());
%>
`
jsp
`<%
ServletContext ctx = application;
synchronized(ctx) {
Integer total = (Integer) ctx.getAttribute("totalHits");
total = (total == null ? 1 : total + 1);
ctx.setAttribute("totalHits", total);
out.println("Total Hits: " + total);
}
%>
`
But remember synchronization hurts performance—better to use `AtomicInteger` stored in the context.
3. Summary Checklist
1. No instance variables in your JSP.
2. Use local variables for all per-request data.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/17
3. Store any shared counters or state in thread‐safe classes (e.g. `AtomicInteger`).
4. Prefer moving logic into servlets, beans, or custom tags—and keep JSPs for view‐only.
5. If you really need single‐threaded JSP, you can still use
jsp
By following these practices, your JSP pages will behave correctly even under concurrent load.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/17