0% found this document useful (0 votes)
7 views17 pages

JSP Scopes and Anatomy

The document explains JSP (JavaServer Pages) scopes, anatomy, and lifecycle, detailing four scopes: page, request, session, and application, along with examples of their usage. It outlines the structure of a JSP page, including directives, declarations, scriptlets, expressions, comments, standard actions, and template text. Additionally, it describes the lifecycle of a JSP page from translation to cleanup, and provides an example of a servlet filter that restricts access based on IP address.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views17 pages

JSP Scopes and Anatomy

The document explains JSP (JavaServer Pages) scopes, anatomy, and lifecycle, detailing four scopes: page, request, session, and application, along with examples of their usage. It outlines the structure of a JSP page, including directives, declarations, scriptlets, expressions, comments, standard actions, and template text. Additionally, it describes the lifecycle of a JSP page from translation to cleanup, and provides an example of a servlet filter that restricts access based on IP address.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

JSP Scopes and Anatomy

a) Write different scopes of JSP objects with example:


b) Write briefly the anatomy of a JSP page.
Explain how a JSP page works.
ans in detail

a) Scopes of JSP Objects

JSP defines four standard scopes in which you can store and retrieve objects. They determine the
lifecycle and visibility of attributes you set.

Scope Description Example Usage


Lives only for the
duration of the `jsp\n<%\n // set an attribute in page scope\n
page current JSP page. Not pageContext.setAttribute(\"msg\", \"Hello
visible to other pages Page\");\n%>\n${msg}\n`
or requests.

Lives for the duration `jsp\n<%\n // in first.jsp\n


of a single HTTP request.setAttribute(\"user\", \"Alice\");\n
request. Shared RequestDispatcher rd =
request
among any request.getRequestDispatcher(\"second.jsp\");\n
includes/forwards in rd.forward(request, response);\n%>\n`<br/>In second.jsp:
that request. `${user}` yields “Alice.”

Lives as long as the


`jsp\n<%\n session.setAttribute(\"cartSize\",
user’s HTTP session
session 3);\n%>\nYou have ${sessionScope.cartSize} items in your
(until timeout or
cart.\n`
invalidation).

Lives for the entire `jsp\n<%\n // in a servlet or JSP init\n


web application’s application.setAttribute(\"startupTime\", new
application
lifetime (shared by all java.util.Date());\n%>\nStarted at:
users). ${applicationScope.startupTime}\n`

Notes on accessing scoped attributes

JSTL / EL: `${requestScope.foo}`, `${sessionScope.foo}`, `${applicationScope.foo}`, or


simply `${foo}` (resolves in page→request→session→application order).

Scriptlets: `pageContext.getAttribute("foo")`, `request.getAttribute("foo")`, etc.

b) Anatomy of a JSP Page

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)

Syntax: `<%@ directive attribute="value" %>`


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/17
Common directives:
`page` (e.g. `<%@ page contentType="text/html; charset=UTF-8" import="java.util.*" %>`)

`include` (static include: `<%@ include file="header.jsp" %>`)


`taglib` (declare custom tag libraries)
2. Declarations

Declare member variables or methods in the generated servlet


Syntax: `<%! int counter = 0; public String greet(){ return "Hi"; } %>`

3. Scriptlets
Inline Java code inserted into the `_jspService()` method

Syntax: `<% /* Java code here */ %>`


4. Expressions
Evaluate a Java expression and convert to string, inserting result into output

Syntax: `<%= new java.util.Date() %>`

5. Comments
JSP comment (not sent to client): `<%-- This won’t appear in HTML --%>`

HTML comment (sent to client): `<!-- visible in page source -->`

6. Standard Actions

XML-like tags to perform common tasks, e.g.:


`<jsp:include page="footer.jsp"/>`

`<jsp:useBean id="user" class="com.example.User" scope="session"/>`

`<jsp:setProperty name="user" property="*"/>`

7. Expression Language (EL)


Simplifies access to scoped attributes and implicit objects: `${param.id}`, `${cookie.user}`,
`${header["User-Agent"]}`

8. Template Text

Any static content (HTML, CSS, JavaScript) outside of JSP tags is copied verbatim to the
response.

Example JSP Page

jsp

`<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<%@ page import="java.util.Date" %>

<%-- Declaration: a member variable --%>


<%! int visitCount = 0; %>

<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>

<%-- Include footer --%>


<jsp:include page="footer.jsp"/>
</body>
</html>
`

How a JSP Page Works (Lifecycle)

1. Translation

The JSP engine (container) translates `yourPage.jsp` → `yourPage_jsp.java` (a servlet source).


2. Compilation

`yourPage_jsp.java` is compiled into `yourPage_jsp.class`.

3. Loading & Initialization

Container loads the servlet class.


Calls `jspInit()` once—useful for one-time setup.

4. Request Processing

For each HTTP request:


1. Container creates `HttpServletRequest` and `HttpServletResponse` objects.

2. Calls `_jspService(request, response)`—this method contains all your scriptlets,


expressions, and template text.

3. Output is written to response’s `JspWriter`.

5. Cleanup
When the container decides to unload the JSP (e.g., application shutdown or redeploy), it calls
`jspDestroy()`—for cleanup.

Flow Diagram

pgsql

`Client HTTP Request



Container checks if JSP servlet exists & is up-to-date

(Re)translate → (Re)compile if needed

Load servlet class → jspInit()

_jspService(request, response) executes

Write HTML to client

jspDestroy() on unload
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/17
Key Takeaways

Scopes govern how long and where your data lives.


Anatomy: directives & declarations (class-level), scriptlets & expressions (method-level), actions &
EL (simplified, tag-based).

Lifecycle: Translate → Compile → Init → Service → Destroy.


JSPs are simply servlets under the hood, with conveniences for embedding HTML and for accessing
Java EE resources.

Uploaded image
same

Here are the answers to each part:

1. Four JSP Implicit Objects and Their “Scope”


In JSP you always have the following implicit objects available. Four of these map naturally onto the four
standard JSP scopes:

Implicit
Java Type JSP Scope Description
Object

Gives access to all the other


implicit objects and page
pageContext `javax.servlet.jsp.PageContext` page
attributes. Lives only for
this JSP.
Represents the current
HTTP request; shared with
request `javax.servlet.http.HttpServletRequest` request any `<jsp:include>` or
forward, lives for one
request.
Tied to the user’s session;
session `javax.servlet.http.HttpSession` session lives until the session times
out or is invalidated.

Shared across the whole


web app; lives until the app
application `javax.servlet.ServletContext` application
is undeployed or the
container shuts down.

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.

2. Creating and Using a JavaBean in JSP


2.1. The Three Standard JSP Bean Tags

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

Suppose you have a simple JavaBean:

java

`// src/com/example/User.java
package com.example;

public class User {


private String name;
private int age;

public User() { }

public String getName() { return name; }


public void setName(String name) { this.name = name; }

public int getAge() { return age; }


public void setAge(int age) { this.age = age; }
}
`

JSP page (`user.jsp`)

jsp

`<%@ page contentType="text/html; charset=UTF-8" %>

<html>
<head><title>Bean Demo</title></head>
<body>

<!-- 1) Declare or locate the bean in session scope -->


<jsp:useBean id="user"
class="com.example.User"
scope="session" />

<!-- 2) Populate its properties from request parameters -->


<jsp:setProperty name="user" property="name" value="Alice" />
<jsp:setProperty name="user" property="age" value="30" />
<!-- or: <jsp:setProperty name="user" property="*" /> to map all matching params -->

<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>`

Creates a new `User` object if none exists in the given scope


Otherwise returns the existing one

`<jsp:setProperty>`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/17
Sets one or more bean properties
`<jsp:getProperty>`

Retrieves and prints a bean property

3. Differences Between Include Directive vs. Include Action Tag


Feature Include Directive Include Action Tag
`<jsp:include page="header.jsp"
Syntax `<%@ include file="header.jsp" %>`
/>`
When it's processed Translation time (JSP → servlet) Request time (every request)
Static text merge: source files are Dynamic include: invokes a sub-request
Mechanism
concatenated before compilation and inserts its output

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)

Putting It All Together

Scopes & Implicit Objects


Map `pageContext`→page, `request`→request, `session`→session, `application`→application.

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:

1. The Java filter class (with annotations)

2. A sample `web.xml` mapping (if you prefer XML over annotations)

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

1. The Filter Class


java

`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;

@WebFilter("/*") // intercept all URLs


public class IPAllowFilter implements Filter {
// The only allowed IP
private static final String ALLOWED_IP = "172.16.4.248";

@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
}
}
`

We annotate with `@WebFilter("/*")` so all incoming URLs hit this filter.

In `doFilter()`, we check `request.getRemoteAddr()` against the allowed IP.


If it matches, we call `chain.doFilter(…)` so the request proceeds; otherwise we forward to
`/error.jsp`.

2. (Optional) `web.xml` Configuration


If you prefer not to use annotations, you can instead declare the filter in `WEB-INF/web.xml`:

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

`<%@ page contentType="text/html; charset=UTF-8" %>


<html>
<head>
<title>Access Denied</title>
</head>
<body>
<h1>403 – Forbidden</h1>
<p>Your IP (<%= request.getRemoteAddr() %>) is not authorized to access this application.</p>
</body>
</html>
`

4. Packaging & Deployment on Tomcat


1. Compile & package

Make sure your project follows the standard Maven/Gradle layout (or plain `WEB-INF/classes`,
`WEB-INF/lib`).

If using Maven, you’d do `mvn package` to produce `target/yourapp.war`.


2. Deploy

Copy `yourapp.war` into Tomcat’s `webapps/` folder.

Start (or restart) Tomcat.

Tomcat auto-explodes the WAR and your filter will be active.


3. Test

From a client on IP `172.16.4.248`: you should see your normal pages.

From any other IP: you’ll get forwarded to `error.jsp`.

Summary

IPAllowFilter intercepts every request.


Only `172.16.4.248` is passed through; others are forwarded to a JSP error page.

You can configure the filter via annotations or `web.xml`.

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.

skip 2nd question

Below are the answers to (i) and (iii); as requested, we’re skipping the filter question.

i) When Is `JSESSIONID` Created?

On first session creation.


By default, every JSP/Servlet-based web app has session support enabled. The container will create
an `HttpSession`—and issue a session identifier (`JSESSIONID`)—as soon as you call:

java

`HttpSession session = request.getSession(); // creates a new session if none exists


`

or any JSP page that uses the implicit `session` object (which under the covers invokes
`request.getSession()`).

Cookie vs. URL rewriting.

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.

1. Request arrives with no session cookie/ID.


2. Your code (or JSP engine) calls `request.getSession()`.

3. Container instantiates a new `HttpSession` object, generates a unique `JSESSIONID`, stores it


server-side, and sends the ID back to the client.
4. Subsequent requests from that client include the `JSESSIONID`, allowing the container to look
up the same `HttpSession`.

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

`<%@ page session="false" %>


`

which disables the implicit `session` object and prevents auto-creation of `JSESSIONID`.

iii) Creating and Using a Custom Tag in JSP

Custom tags let you encapsulate reusable presentation logic in tag libraries. Here’s a simple end-to-end
example.

1. Write the Tag Handler Class

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;

public class HelloTag extends SimpleTagSupport {


private String name = "World";

// setter for the 'name' attribute


public void setName(String name) {
this.name = name;
}

@Override
public void doTag() throws IOException {
JspWriter out = getJspContext().getOut();
out.print("Hello, " + name + "!");
}
}
`

Extends `SimpleTagSupport` (JSP 2.0+).


Defines a `name` attribute via its setter.

In `doTag()`, writes to the JSP output.

2. Declare the Tag in a TLD File

Create `/WEB-INF/tlds/mytags.tld`:

xml

`<?xml version="1.0" encoding="UTF-8"?>


<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">

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>
`

`<uri>` is an arbitrary identifier you’ll use in the JSP.


Defines one `<tag>` named `hello`, backed by our `HelloTag` class, with an optional `name`
attribute.

3. Use the Tag in Your JSP

jsp

`<%@ taglib prefix="mt" uri="http://example.com/mytags" %>


<html>
<head><title>Custom Tag Demo</title></head>
<body>
<!-- Default name -->
<mt:hello/>

<br/>

<!-- Override 'name' attribute -->


<mt:hello name="Souvik"/>
</body>
</html>
`

The `<%@ taglib %>` directive binds the `mt` prefix to your TLD’s URI.

`<mt:hello/>` invokes `HelloTag.doTag()`.

4. Deployment Notes

1. Compile your tag handler into `WEB-INF/classes/com/example/tags/HelloTag.class`.


2. Place `mytags.tld` under `WEB-INF/tlds/`.

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.

Once deployed, any JSP in your app can:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/17
jsp

`<%@ taglib prefix="mt" uri="http://example.com/mytags" %>


<mt:hello name="Jane"/>
`

…and it will render:

`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.

Below are two parts:

1. Handling Uncaught Errors with the `page` Directive


JSP lets you declaratively forward uncaught exceptions to a dedicated error page. You use two attributes
of the `<%@ page %>` directive:

1. `errorPage` on your “normal” JSP


2. `isErrorPage` on the JSP that will handle the exception

1.1. Example “Main” JSP

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/17
jsp

`<%@ page contentType="text/html; charset=UTF-8"


errorPage="error.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>
`

`errorPage="error.jsp"` tells the container:


“If any exception propagates out of this JSP, forward to `/error.jsp`.”

1.2. Example Error-Handling JSP

jsp

`<%@ page contentType="text/html; charset=UTF-8"


isErrorPage="true" %>

<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.

2. Sample Servlet Code Generated for a Simple JSP


Given this JSP fragment:

jsp

`<%! String msg = "Hello World!"; %>


<% out.println(msg); %>
<%= msg %>
`

A JSP engine will translate it into a servlet something like:

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.*;

public final class example_jsp extends HttpJspBase


implements JspSourceDependent {

// Declaration block → becomes a field


private String msg = "Hello World!";

public void _jspService(HttpServletRequest request,


HttpServletResponse response)
throws java.io.IOException, ServletException {

// Standard JSP setup:


JspFactory _jspxFactory = JspFactory.getDefaultFactory();
PageContext pageContext = _jspxFactory.getPageContext(
this, request, response, null, true, 8192, true);
ServletContext application = pageContext.getServletContext();
ServletConfig config = pageContext.getServletConfig();
JspWriter out = pageContext.getOut();
HttpSession session = request.getSession();

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);
}
}

// (plus any required methods, e.g. getDependants, jspInit, jspDestroy…)


}
`

Breakdown

`<%! … %>` → becomes a field (`private String msg…`) in the servlet class.
`<% out.println(msg); %>` → in `_jspService` you see `out.println(msg);`.

`<%= msg %>` → translated to `out.print(msg);`.


Boilerplate for obtaining `PageContext`, `JspWriter out`, handling exceptions, and finally releasing
the context.

With these two examples you can see:

Uncaught error handling via `errorPage`/`isErrorPage`.


How JSP fragments translate into the Java servlet class and its `_jspService()` method.

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.

1. The (Deprecated) `SingleThreadModel` Approach


You can turn off multithreading for a JSP by declaring:

jsp

`<%@ page isThreadSafe="false" %>


`

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

Deprecated in Servlet 2.4 and later


Poor performance and scalability
Still doesn’t protect against shared objects in application or session scope

2. Recommended Best Practices for Thread Safety


2.1. Avoid Instance Variables in JSP

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);
%>
`

✋ Never do this in JSP:


jsp

`<%!
// 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
%>
`

2.2. Use Only Thread-Safe Scopes or Synchronization

Request scope (`request.setAttribute("foo", …)`) is inherently per-thread, so safe.


Session/application scope: if you store mutable objects here, make them thread-safe (e.g. use
`java.util.concurrent` classes like `AtomicInteger`, synchronized wrappers, or handle updates
inside a synchronized block).

jsp

`<%
AtomicInteger visits =
(AtomicInteger) session.getAttribute("visits");
if (visits == null) {
visits = new AtomicInteger(0);
session.setAttribute("visits", visits);
}
out.println("Visits: " + visits.incrementAndGet());
%>
`

2.3. Push Business Logic Out of JSP

Move stateful or synchronized code into:

Servlets (one per request)


JavaBeans or helper classes that you can test and make thread-safe explicitly
Tag handlers (stateless ones)

2.4. Synchronize Only Critical Sections

If you absolutely must guard a shared resource, do it sparingly:

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

`<%@ page isThreadSafe="false" %>


`

but it’s not recommended in modern applications.

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

You might also like