JSP (JavaServer Pages) has four types of scopes that determine how long an object is available and where it can be accessed:
pagescope- Lifetime: Exists as long as the current page is being processed.
- Access: Only within the same JSP page.
- Default scope in JSP.
- Example:
<jsp:useBean id="bean1" class="ExampleBean" scope="page"/>
requestscope- Lifetime: Exists until the request is completed (across multiple JSPs/Servlets if forwarded).
- Access: Any component that handles the request.
- Used for: Request forwarding, passing data between pages.
- Example:
<jsp:useBean id="bean2" class="ExampleBean" scope="request"/>
sessionscope- Lifetime: Exists as long as the session is active (until browser closed or timeout).
- Access: Accessible across multiple requests from the same user.
- Used for: User login sessions, shopping carts, etc.
- Example:
<jsp:useBean id="bean3" class="ExampleBean" scope="session"/>
applicationscope- Lifetime: Exists as long as the web application is running.
- Access: All JSPs and servlets can access it.
- Used for: Application-wide data (counters, config).
- Example:
<jsp:useBean id="bean4" class="ExampleBean" scope="application"/>
🧾 HTML Form (InterestForm.html)
<!DOCTYPE html>
<html>
<head>
<title>Simple Interest Form</title>
</head>
<body>
<h2>Simple Interest Calculator</h2>
<form action="calculateInterest.jsp" method="post">
Principal: <input type="number" name="principal" required><br><br>
Time (in years): <input type="number" name="time" required><br><br>
Rate (per annum): <input type="number" name="rate" required><br><br>
<input type="submit" value="Calculate Interest">
</form>
</body>
</html>
📄 JSP File (calculateInterest.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Interest Result</title>
</head>
<body>
<%
// Read form parameters
String principalStr = request.getParameter("principal");
String timeStr = request.getParameter("time");
String rateStr = request.getParameter("rate");
// Parse values
double principal = Double.parseDouble(principalStr);
double time = Double.parseDouble(timeStr);
double rate = Double.parseDouble(rateStr);
// Calculate simple interest
double interest = (principal * time * rate) / 100;
%>
<h2>Interest Calculation Result</h2>
<p>Principal: <%= principal %></p>
<p>Time: <%= time %> years</p>
<p>Rate: <%= rate %>%</p>
<h3>Simple Interest: <%= interest %></h3>
</body>
</html>